Posts Tagged ‘python’

Using CherryPy for webform authentication

Sunday, March 7th, 2010

If you are using CherryPy, I can recommend the webform-based authentication that Arnar Birgisson wrote for ease of use and extensability.

After trying out the included authentication models with CherryPy (I’m using 3.1.2, the last stable version at the moment of writing), I was disappointed in the results. Then I stumbled over a recommandation from someone on Nabble, a web-based programmar’s discussion forum, which pointed to the following wiki page on the CherryPy site:

http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions

The complete program code plus examples are on the page and are well explained.

You can have a skeleton login system (using a hardcoded dictionary) up and running in literally half an hour !

  • Just copy/paste the code on the page and save it as auth.py in your cherrypy script dir.
  • Add the hardcoded dictionary containing username and passwords to it (or script the db access, see the example included)
  • Put ‘require()’ everywhere on your cherrypy pages that need to have login protection – additionally, you can also have roles so that only admins can access certain pages.

Early last week I replaced that hardcoded dictionary and built the db lookup query for the login. Once that was working, I added a ‘my profile’ page to the application I’m working on.  Then I thought it would be nice for the admin to have a ‘create user’ form in the admin section to add users. Done that as well, using the jquery-ui to create tabs and seperate content in the admin section.

All in all, a nice week of nice work.

I’m starting to think this might make it’s way to my hosting server one of the coming weeks…  although I need to do some more work on showing the user only his keywords and not all the keywords, as well as doing something with the keywords to use them better.

Oh and one more thing: this works better under SSL than in the clear http: sky !

Simple Python threading.Thread example using Queue

Wednesday, February 3rd, 2010

I managed to write a really simple example of using threads in Python that I hope will give more insight on how to adapt my other programming stuff. And re-use this later on, in case I need to revisit this again it would be handy not to scour the internet again to assemble the bits and pieces of threading with Python.

The example below uses 3 threads, and processes 10 pairs of numbers (tuples) that I put in a list.

  1. # Our list of work todo
  2. inputlist_ori = [ (5,5),(10,4),(78,5),(87,2),(65,4),(10,10),(65,2),(88,95),(44,55),(33,3) ]

Those numbers are divided over those 3 threads by the Queue system.

The Queue system itself is limited to 5 slots, although this could easily be changed to more or less. You will notice in the console print that the message “Waiting for threads to finish.” appears after the fifth result, indicating that the queues are being used and the main program has continued on.

After putting everything in the queue system, the program waits for the threads to finish using the .join() function.

All spawned threads keep on being active, running forever, accepting jobs – that is, until the queue is empty, at which point they shut down.

I based most of my simple example on the examples in the Python threading tutorial (.pdf) work of Norman Matloff and Francis Hsu that I referenced before in a previous blog post. However, while their examples undoubtedly do more and are more extensive, they are also more complex. This example is deliberately made as simple as possible so to understand the basic principles of threading and the queue system.

Things I stumbled over:

  • Duh! You spawn the threads before you fill up the queues with stuff todo…
  • When printing out things to the console or python shell, things got jumbled because different threads took over from each other – to solve that I used the threading.Lock().acquire() and threading.Lock().release() to make sure that a thread could finish printing. Not sure if I understand completely all the possibilities this offers.
  • Still a bit stumped on getting more info, name, etc on the thread that is running at the moment – haven’t figured that out yet how to do that.

Feel free to comment and ask questions – if you can improve this program, please let me know !

  1. # threading test
  2. # Alex Boschmans
  3. # www.boschmans.net
  4. # January 2010
  5.  
  6. #
  7. # IMPORT SECTION
  8. #
  9. import threading, Queue
  10.  
  11. #
  12. # Variables setup
  13. #
  14. THREAD_LIMIT = 3                # This is how many threads we want
  15. jobs = Queue.Queue(5)           # This sets up the queue object to use 5 slots
  16. singlelock = threading.Lock()   # This is a lock so threads don’t print trough each other (and other reasons)
  17.  
  18. # Our list of work todo
  19. inputlist_ori = [ (5,5),(10,4),(78,5),(87,2),(65,4),(10,10),(65,2),(88,95),(44,55),(33,3) ]
  20.  
  21. #
  22. # This is called from the main function
  23. # It spawns the threads, fills up the queue with work items that the threads will use
  24. # And then waits for the threads to finish
  25. # This could use some more try:except code…
  26. #
  27. def draadje(inputlist):
  28. print "Inputlist received…"
  29. print inputlist
  30.  
  31. # Spawn the threads
  32. print "Spawning the {0} threads.".format(THREAD_LIMIT)
  33. for x in xrange(THREAD_LIMIT):
  34. print "Thread {0} started.".format(x)
  35. # This is the thread class that we instantiate.
  36. workerbee().start()
  37.  
  38. # Put stuff in queue
  39. print "Putting stuff in queue"
  40. for i in inputlist:
  41. # Block if queue is full, and wait 5 seconds. After 5s raise Queue Full error.
  42. try:
  43. jobs.put(i, block=True, timeout=5)
  44. except:
  45. singlelock.acquire()
  46. print "The queue is full !"
  47. singlelock.release()
  48.  
  49. # Wait for the threads to finish
  50. singlelock.acquire()        # Acquire the lock so we can print
  51. print "Waiting for threads to finish."
  52. singlelock.release()        # Release the lock
  53. jobs.join()                 # This command waits for all threads to finish.
  54.  
  55. #
  56. # Main thread class – based on threading.Thread
  57. # This class is cloned/used as a thread template to spawn those threads.
  58. # The class has a run function that gets a job out of the jobs queue
  59. # And lets the queue object know when it has finished.
  60. #
  61. class workerbee(threading.Thread):
  62. def run(self):
  63. # run forever
  64. while 1:
  65. # Try and get a job out of the queue
  66. try:
  67. job = jobs.get(True,1)
  68. singlelock.acquire()        # Acquire the lock
  69. print "Multiplication of {0} with {1} gives {2}".format(job[0],job[1],(job[0]*job[1]))
  70. singlelock.release()        # Release the lock
  71. # Let the queue know the job is finished.
  72. jobs.task_done()
  73. except:
  74. break           # No more jobs in the queue
  75.  
  76. #
  77. # Executes if the program is started normally, not if imported
  78. #
  79. if __name__ == ‘__main__’:
  80. # Call the mainfunction that sets up threading.
  81. draadje(inputlist_ori)

Sigh. I just finished adding spaces to show where a def ends, and the damn code highlighter removed it again. Grrrrrr. If you want a copy of the code, let me know and I’ll update this post with a zipped copy of it.

Not using regular expressions (re or regex) to find a #hashtag (python).

Wednesday, January 27th, 2010

First, a quick reminder for myself: there’s an extremely good guide to regex on Andrew M. Kuchling’s pages.

Secondly, you don’t really *need* regex to parse for hashtags in a tweet – it’s a bit of overkill. The following code will do as well, and was written in 1 minute after searching 15 minutes in regex how to make certain to include hyphens ( – ) and other non-characters if they are put into the hashtag.

The regular expression that I find works quite well for all hashtags that don’t have a hyphen in it:

  1. >>> hashtag = "This is a #hashtag #test-link #a should#not#work"
  2. >>> x = re.compile(r\B#\w+’)
  3. >>> x.findall(hashtag)
  4. [‘#hashtag’, ‘#test’, ‘#a’]

So the above code correctly finds all words beginning with a hashtage, and not the ones that contain a hashtag inside the word. Note that the hyphen and the word after it is not included.

This is the short code I wrote that does all I want:

  1. >>> hashtag = "This is a #hashtag #test-link #a should#not#work"
  2. >>> for word in hashtag.split():
  3.         if word[0] == "#":
  4.                 print word             
  5. #hashtag
  6. #test-link
  7. #a

In section 6 of the above-mentioned guide, Andrew states that in some cases string methods (like split) are faster than using regex. For simplicity, I’m going to use the latter code.

Update: Grrr – discovered that the tweets I am processing are in html so have href tags around them – which means ofcourse that there are no blanks for me to split words in. After another unsuccessful session with regex and just to continue I’ve used the BeautifulSoup html parsing library to get around that by stripping out all tags and then splitting the sentence up again. Probably not as efficient as immediately using regex, I’ll have to revisit this in the future.

Using threads in Python

Tuesday, January 26th, 2010

I’ve been trying to setup threading in Python, so that in the back-end of my service system that I’m developing I can query more than one source at the same time. So instead of querying one server and waiting for feedback, I can launch 10 threads and thus query 10 servers and process each server’s feedback via it’s own thread.

So a very vague, generalising definition of a thread is an independent ‘process’ that performs a job that you give it. You can control how many threads that you launch. Each thread is a copy of the original thread that you describe (in essence a python def function that has been wrapped in a thread class).

Right now, my understanding of threads is a bit confused. So far it seems that threading has several different manners of implementing them:

  • using a number of threads that you launch, use, and forget about them (they go away)
  • improving on that by putting those threads in a thread pool, and when a thread finishes, re-using it for the next job (so you have  5 threads but 10 jobs to do, those five threads take five jobs, and the first thread that finishes takes on the sixth job, the second thread to finish the seventh job, and so on)
  • the final step seems to be (I haven’t got that far in my implementation) to set up worker bees that are managed by one thread (a better description is promised, as soon as I have understood it!)

Since I’ve been scouring the net for information over threads, here is a list of resources that discuss, give examples, and explain threads – it’s useful for me to refer to, it might be useful for you as well :

  • DaveN has an extensive post, with examples, building up gradually. It’s only at the end that you read that the code shown has never been run, which is a bit of a letdown. Still worth a good read though !!
  • A very thorough 25-page pdf documents that starts from the beginning is available on the site of UC Davis, University of California. It goes into all the nitty gritty details.
  • An example that uses workers in threads is found on the blog of Danial Taherzadeh.
  • Another one that discusses using multiple queues chained together can be found on IBM’s developerworks site.
  • And the blog post from Halotis that started my looking into threads…

Right now I’m using threads in a thread pool, but I’m not doing something right – I noticed that while I have 10 jobs to do, only the first five get done, and the others ‘disappear’.

I guess the only way to get it working is to continue reading the information above until it makes sense. Sometimes I wonder if I’m not slightly masochistic, looking for challenges like that… ai me poor pounding head ! :-)

What about flex on this blogpost ?

Saturday, December 19th, 2009

For those few regular readers out there, they have probably noticed that I no longer post regularly about Adobe Flex.

Please be assured that this is not out of the picture ! Rather, I wanted to learn Flex enough to get by in it. It’s been *very* interesting, but also very hard sometimes to wrap my head around Actionscript and MXML. Now that I know a bit about what I can do with Flex, I’ve started again with Python and more specifically with CherryPy.

CherryPy is a very easy-to-use web framework that you can use to set up your own webserver in a flash. It provides a basic syntax for setting up the webservice, then scurries out of the way, letting you ‘get on with it’, whatever that may be.

Currently I’m setting up a local Webserver (using CherryPy) and this is where most of my time has gone to.

Once the python application on there has been created (and most of it has) I then will head back to Flex and it’s usages as a reporting tool – I’ll be trying to use PyAMF as the glue between python functions and Flex datagrids.

Anyways, more on that later…

Feedparser.py and it’s uses…

Saturday, December 19th, 2009

I recently discovered feedparser.py, a library written by Mark Pilgrim that is amazing if you want to use python to consume rss feeds. It ‘normalizes’ the different versions of rss/atom out there into one request that you can use consistently. Doesn’t matter if it’s atom 0.1 or 0.3

A few links that are interesting together with feedparser.py as they show it’s usage:

I’m constantly amazed about the quality python code that is out there and you can just find via a simple google query. It certainly makes me think that choosing Python over, say Perl, was a good decision.

As for using feedparser.py to put relevant tweets on your website, note that you can also use javascript to achieve the same thing; go here for some twitter.com goodies and an explanation on how to set this up.

Cleaning up user input variables on the web (Python)

Saturday, December 5th, 2009

Only recently I’ve discovered the power of ‘re’ the python regular expression library. Instead of writing long functions that process text character by character to add or remove stuff, you use re, write and expression in regex that achieves what you want and basta! in a few lines things get done.

For example the following function will remove any html tags (preventing Cross Site Scripting) and escape the rest of whatever the user types in:

  1. # Remove html tags and escape the input
  2. def scrapeclean(text):
  3. —-# This matches open and closing tags and what’s between them
  4. —-x = re.compile(r‘<[^<]*?/?>’)
  5. —-# Replace to nothing using sub and escape what’s leftover and return the result all in one line!
  6. —-return cgi.escape(x.sub(,text))

Remove the dashes when you copy the code – they were added to show the necessary indentation. And for full disclosure : I took the compile statement from the following site (I’m not a regex expert).

So you can call this function from somewhere in your python code and the result will be ’scraped clean’ of all tags beginning with < and ending with > plus any ampersands other other special characters get to be ‘escaped’.

YMMV – this is very likely not a complete protection against all the things a hacker can input in your website, but it’s certainly a start.

Python Package Manager

Wednesday, November 11th, 2009
Python Package Manager Logo

Python Package Manager Logo

The Python Package Manager is here, a visual tool for the python developer to find and install all the necessary packages.

It shows you what is already installed on your system, with the option to deinstall the packages, and by typing into the search box you can find additional packages and install them, all graphically. It’s supposed to be cross-platform, but the homepage of the developer only provides a windows download option.

I just hope this gets used and keeps being supported, as it is a lot handier than using the command line ! I do think you still need easy_install and wxpython/wxwidgets though…

Getting easy_install to run for Python 2.6

Thursday, May 7th, 2009

StackOverflow is a great new website for all kinds of programmers.

Flex, Python or any other language programmers can ask questions there and receive answers, or usually, find out their questions have already been asked before and the answers are already there.

Python 2.6 has just come out, and a very easy install tool (called, appropriately, easy_install) has not yet been ported to the windows version of Python 2.6.

StackOverflow has the question, and several answers !

Once easy_install is installed and has been added to your PATH, it’s a breeze to install additional site-packages to your python setup, like pyodbc or the cheetah templating engine or pyamf just by running the command ‘easy_install <programname>’ in a dos box where <programname> is the name of your program.

Version 1.8 of CSV2XML is out

Sunday, April 19th, 2009

Thanks to a comment from a user of the program who had problems getting the script to process csv files on the mac, I’ve updated the script to version 1.8 so it will now open them without first needing to save the file in unix format when exporting to csv from Office for Mac.

For those of you who noted the version skip, version 1.7 has not been released, but just includes a simple test to see if the first field is empty or not. If empty the line is dropped. It’s been commented out in the latest version. Since my hosting provider also does python, I have renamed the file to .txt. Simply rename it to .py to have it working.

csv2xml_v18

[For the Pythonistas : I've set the csv module to now open the files in read 'universal' mode]

Archives
Search this blog
My Webhost