473,657 Members | 2,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NNTP binary attachment downloader using asyncore and generators

Howdy,

Sorry if this is a double post. First try seemed to go into
hyperspace.

I'm working on a personal project. It's going to be a multipart
binary attachment downloader that will search alternate servers for
missing pieces. This is the working code so far. It will walk a
newsgroup and download and decode all the single part attachments.
Just change server,user,pas sword,group at the bottom to something less
virtual.

I'm posting this to get some feedback on my use of generators (and
anything else). It's my first time using them in a non-trivial
program, and I'd like to know if there is more 'Pythonic' way I could
be doing any of this.

My email is obviously fake, so responding here would be great.

Thanks in advance,
David Fisher
#!/usr/bin/env python2.3
#
import asyncore
import socket
import os
import uu
import email
#
class Newser(asyncore .dispatcher):

def __init__(self, host,port,user, password,group) :
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.connect( (host,port) )
self.buffer = ''
self.user = user
self.password = password
self.group = group
self.n = 0
self.head = ''
self.body = ''
self.inbuffer = ''
self.dataline = ''
self.handleline = self.handleline _gen()

def handle_connect( self):
pass

def handle_close(se lf):
pass

def writable(self):
return (len(self.buffe r) > 0)

def handle_write(se lf):
print 'sending: ' + self.buffer.str ip()
sent = self.send(self. buffer)
self.buffer = self.buffer[sent:]
if self.buffer:
print 'didnt send whole line' #does this ever happen?
print 'didnt send whole line' #just getting my attention
print 'didnt send whole line' #in case it does

def handle_read(sel f):
self.inbuffer += self.recv(8192)
while 1:
n = self.inbuffer.f ind('\r\n')
if n > -1:
self.dataline = self.inbuffer[:n+2]
self.inbuffer = self.inbuffer[n+2:]
try:
result = self.handleline .next()
if result == 'OK':
pass # everything is groovy
elif result == 'DONE':
self.del_channe l() # group walk is finished
break
else:
print 'something has gone wrong!'
print result
print self.dataline
self.del_channe l()
break
except StopIteration:
print 'should never be here'
print 'why did my generator run out?'
print 'why god? why?!'
print self.dataline
self.del_channe l()
break
else:
break

def handleline_gen( self):
#
# handshakey stuff
# welcome username password group
# after this is set we'll start the message walk
#
if self.dataline[:3] == '200': # welcome, post ok
print self.dataline.s trip()
self.buffer = 'authinfo user ' + self.user + '\r\n'
yield 'OK'
else:
yield 'WTF?! fail welcome? god hates me!'
#
if self.dataline[:3] == '381': # more auth needed
print self.dataline.s trip()
self.buffer = 'authinfo pass ' + self.password + '\r\n'
yield 'OK'
else:
yield 'WTF?! fail authinfo user'
#
if self.dataline[:3] == '281': # auth ok, go to town!
print self.dataline.s trip()
self.buffer = 'group ' + self.group + '\r\n'
yield 'OK'
else:
yield 'WTF?! fail authinfo pass'
#
if self.dataline[:3] == '211': # group
print self.dataline.s trip()
self.buffer = 'next\r\n'
yield 'OK'
else:
yield 'WTF?! fail group'
#
# main state loop
# walk from one message to the next
# issuing HEAD and BODY for each
# never reenter here after we receive '421', no next article
# so we should never issue StopIterator
#
while 1:
#
if self.dataline[:3] == '223': # next
print self.dataline.s trip()
self.buffer = 'head\r\n'
yield 'OK'
elif self.dataline[:3] == '421': # err, no next article
yield 'DONE'
else:
yield 'WTF?! fail next'
#
if self.dataline[:3] == '221': # head
print self.dataline.s trip()
self.head = ''
yield 'OK'
# XXX what am I going to do if the server explodes
while self.dataline <> '.\r\n':
self.head += self.dataline
yield 'OK'
# XXX parse headers here
# XXX decide whether we want body
self.buffer = 'body\r\n'
yield 'OK'
else:
yield 'WTF?! fail head'
#
if self.dataline[:3] == '222': # body
print self.dataline.s trip()
self.body = ''
yield 'OK'
# XXX what am I going to do if the server explodes
while self.dataline <> '.\r\n':
# XXX line-by-line decode here (someday)
self.body += self.dataline
yield 'OK'
self.decode()
self.buffer = 'next\r\n'
yield 'OK'
else:
yield 'WTF?! fail body'

def decode(self):
"""decode message body.
try UU first, just decode body
then mime, decode head+body
save in tempfile if fail"""
tempname = 'temp' + `self.n` + '.txt'
self.n += 1
file(tempname,' wb').write(self .body)
f = file(tempname)
try:
uu.decode(f)
except Exception,v:
print 'uu failed code: ',v
print 'trying MIME'
file(tempname,' wb').write(self .head+self.body )
f = file(tempname)
message = email.message_f rom_file(f)
for part in message.walk():
print part.get_conten t_type()
filename = part.get_filena me()
if filename:
if not os.path.isfile( filename):

file(filename,' wb').write(part .get_payload(de code=True))
print 'yay! MIME!'
os.remove(tempn ame)
else:
print "oops, we've already got one"
else:
print 'yay! UU!'
os.remove(tempn ame)

def main():
mynews = Newser('news.se rver',119,'fish boy','pass','al t.binaries')
try:
asyncore.loop()
except KeyboardInterru pt:
mynews.del_chan nel()
print 'yay! I quit!'

if __name__ == '__main__':
main()

Jul 18 '05 #1
0 1864

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2696
by: Michael Welsh | last post by:
In order to learn sockets in Python I am trying to write a simple group chat server and client. I need a little nudge, please. My question contains some GUI but only as decoration. The root question is asyncore / asynchat. I have read that twisted makes this all simple, but, I wanted to get my hands dirty here for educational purposes. I've managed to build a small echo server with asyncore and asynchat that can handle any number of...
1
1940
by: fishboy | last post by:
Howdy, I'm in middle of a personal project. Eventually it will download multipart binary attachments and look for missing parts on other servers. And so far I've got it to walk a newsgroup and download and decode single part binaries. I thought I'd post the code and see what people think. I'd appreciate any feedback. It's my first program with generators and I'm worried I'm making this twice and hard as it needs to be.
0
1752
by: Tony Meyer | last post by:
Changes in asyncore from 2.3 to 2.4 mean that asyncore.poll() now passes all the sockets in the map to select.select() to be checked for errors, which is probably a good thing. If an error occurs, then handle_expt() is called, which by default logs the error. asyncore.dispatcher creates nonblocking sockets. When connect_ex() is called on a nonblocking socket, it will probably return EWOULDBLOCK (connecting takes time), which may mean...
2
2800
by: Ryan Taylor | last post by:
Hello. I have an ASP.NET application where I allow the user to upload attachments. I upload the attachments as binary data to an image column in sql server. I have managed to upload the data correctly. However, I need to be able to set binary field back to NULL if the user wants to delete an attachmnet. What is the proper way to do this? Thanks in advance. I currently receive the following error.
4
1166
by: Jim | last post by:
Have you seen any NNTP classes that I may use or build upon to build a simple newsreader/downloader? Is there such a class in the .Net framework that I have overlooked? If not, inclusion of RFC documented protocols would certainly be a good idea for a class hierarchy in the .Net classes. You could adopt and extend the classes at will. Who knows......maybe even improve one and get a new RFC implemented.
11
2216
by: Jim | last post by:
Have you seen any NNTP classes that I may use or build upon to build a simple newsreader/downloader? Is there such a class in the .Net framework that I have overlooked? If not, inclusion of RFC documented protocols would certainly be a good idea for a class hierarchy in the .Net classes. You could adopt and extend the classes at will. Who knows......maybe even improve one and get a new RFC implemented.
4
2158
by: olguyilmaz | last post by:
Hi, I am using the Updater Application Block Version 2. I am trying to follow the instructions at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpa... to build a custom downloader (UNC ) So far I was not successfull. Firstly,
5
6638
by: david | last post by:
I'm developing a program that runs using an asyncore loop. Right now I can adequately terminate it using Control-C, but as things get refined I need a better way to stop it. I've developed another program that executes it as a child process using popen2.Popen4(). I was attempting to use signals to stop it (using os.kill()) but I keep running into a problem where sending the signal causes an infinite loop of printing the message...
0
1340
by: canistel | last post by:
Hi, I have a little python webservice that I created, and in one of the methods I need to store some binary data that was "posted"... I want to do something like this, but it doesn't work. username = form.get("username", "") message = form.get("message", "") attachment = form.get("attachment", None) .... c.execute("""INSERT INTO Message (username, message, attachment) VALUES (%s, %s, %s)""", (username, message, attachment))
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.