web.py :  » IDE » PIDA » pida-0.6beta3 » pida » utils » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » IDE » PIDA 
PIDA » pida 0.6beta3 » pida » utils » web.py
# -*- coding: utf-8 -*-
"""
    :copyright: 2005-2008 by The PIDA Project
    :license: GPL 2 or later (see README/COPYING/LICENSE)
"""

import base64

from urllib import urlencode
from urllib2 import urlopen,Request

from pida.utils.gthreads import AsyncTask

def fetch_url(url, content_callback, data={}, auth=None):
    """
    Asynchronously fetch a URL.

    It takes these arguments:

        ``url``: the url to fetch

        ``content_callback``: A function that is called with the URL's content

        ``data`` (optional): Additional POST data

        ``auth`` (optional): A tuple in the format (username, password) that's
                             used for http authentication

    """
    req = Request(url)

    if auth:
        base64string = base64.encodestring('%s:%s' % auth)[:-1]
        req.add_header("Authorization", "Basic %s" % base64string)

    if data:
        urlargs = (req, urlencode(data))
    else:
        urlargs = (req,)

    def _fetcher():
        try:
            f = urlopen(*urlargs)
            content = f.read()
            url = f.url
        except Exception, e:
            content = str(e)
            url = None
        return url, content

    task = AsyncTask(_fetcher, content_callback)
    task.start()

if __name__ == '__main__':
    def cc(url, data):
        print url, data
        gtk.main_quit()

    fetch_url('http://google.com/sdfsdfsdf', cc)
    import gtk
    gtk.threads_init()
    gtk.threads_enter()
    gtk.main()
    gtk.threads_leave()

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.