• Facebook
  • Twitter
  • Reddit
  • StumbleUpon
  • Digg
  • email

All Samples(5712)  |  Call(4801)  |  Derive(0)  |  Import(911)
Encode a sequence of two-element tuples or dictionary into a URL query string.

If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.

If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.

        def urlencode(query, doseq=0):
    """Encode a sequence of two-element tuples or dictionary into a URL query string.

    If any values in the query arg are sequences and doseq is true, each
    sequence element is converted to a separate parameter.

    If the query arg is a sequence of two-element tuples, the order of the
    parameters in the output will match the order of parameters in the
    input.
    """

    if hasattr(query,"items"):
        # mapping objects
        query = query.items()
    else:
        # it's a bother at times that strings and string-like objects are
        # sequences...
        try:
            # non-sequence items should not work with len()
            # non-empty strings will fail this
            if len(query) and not isinstance(query[0], tuple):
                raise TypeError
            # zero-length sequences of all types will get here and succeed,
            # but that's a minor nit - since the original implementation
            # allowed empty dicts that type of behavior probably should be
            # preserved for consistency
        except TypeError:
            ty,va,tb = sys.exc_info()
            raise TypeError, "not a valid non-string sequence or mapping object", tb

    l = []
    if not doseq:
        # preserve old behavior
        for k, v in query:
            k = quote_plus(str(k))
            v = quote_plus(str(v))
            l.append(k + '=' + v)
    else:
        for k, v in query:
            k = quote_plus(str(k))
            if isinstance(v, str):
                v = quote_plus(v)
                l.append(k + '=' + v)
            elif _is_unicode(v):
                # is there a reasonable way to convert to ASCII?
                # encode generates a string, but "replace" or "ignore"
                # lose information and "strict" can raise UnicodeError
                v = quote_plus(v.encode("ASCII","replace"))
                l.append(k + '=' + v)
            else:
                try:
                    # is this a sufficient test for sequence-ness?
                    len(v)
                except TypeError:
                    # not a sequence
                    v = quote_plus(str(v))
                    l.append(k + '=' + v)
                else:
                    # loop over the sequence
                    for elt in v:
                        l.append(k + '=' + quote_plus(str(elt)))
    return '&'.join(l)
        


src/r/e/remoteobjects-1.1.1/examples/twitter.py   remoteobjects(Download)
import httplib
from optparse import OptionParser
import sys
from urllib import urlencode, quote_plus
from urlparse import urljoin, urlunsplit
 
from httplib2 import Http
    def get_user(cls, http=None, **kwargs):
        url = '/users/show'
        if 'id' in kwargs:
            url += '/%s.json' % quote_plus(kwargs['id'])
        else:
            url += '.json'
        query = urlencode(filter(lambda x: x in ('screen_name', 'user_id'), kwargs))
    def get_messages(cls, http=None, **kwargs):
        url = '/direct_messages.json'
        query = urlencode(filter(lambda x: x in ('since_id', 'page'), kwargs))
        url = urlunsplit((None, None, url, query, None))
        return cls.get(urljoin(Twitter.endpoint, url), http=http)
 
    @classmethod
    def get_sent_messages(cls, http=None, **kwargs):
        url = '/direct_messages/sent.json'
        query = urlencode(filter(lambda x: x in ('since_id', 'page'), kwargs))
    def get_related(cls, relation, http=None, **kwargs):
        url = '/statuses/%s' % relation
        if 'id' in kwargs:
            url += '/%s.json' % quote_plus(kwargs['id'])
        else:
            url += '.json'
        query = urlencode(filter(lambda x: x in ('screen_name', 'user_id', 'page'), kwargs))
    def friends(cls, http=None, **kwargs):
        query = urlencode(filter(lambda x: x in ('since_id', 'max_id', 'count', 'page'), kwargs))
        url = urlunsplit((None, None, '/statuses/friends_timeline.json', query, None))
        return cls.get(urljoin(Twitter.endpoint, url), http=http)
 
    @classmethod
    def user(cls, http=None, **kwargs):
        url = '/statuses/user_timeline'
        if 'id' in kwargs:
            url += '/%s.json' % quote_plus(kwargs['id'])
        else:
            url += '.json'
        query = urlencode(filter(lambda x: x in ('screen_name', 'user_id', 'since_id', 'max_id', 'page'), kwargs))
    def mentions(cls, http=None, **kwargs):
        query = urlencode(filter(lambda x: x in ('since_id', 'max_id', 'page'), kwargs))
        url = urlunsplit((None, None, '/statuses/mentions.json', query, None))
        return cls.get(urljoin(Twitter.endpoint, url), http=http)
 
 
class Twitter(Http):

src/r/d/Rdbhdb-HEAD/examples/get_no_series_terms.py   Rdbhdb(Download)
# Direct connection; Not through API; Prints rows of tables accounts and branches
 
from urllib import urlencode
from urllib2 import Request, urlopen
 
url = 'http://rdbhost.com/db/'+'s000015'
authcode = 'KF7IUQPlwfSth4sBvjdqqanHkojAZzEjMshrkfEV0O53yz6w6v'
req = Request(url)
flds0 = [('authcode',authcode)]
postdata = urlencode(flds0)
x1 = "DROP TABLE IF EXISTS rdbhdbTest"
try:
    flds1 = [ ('q', x1),('format','xml'),('authcode',authcode)]
    postdata = urlencode(flds1)
    req.add_data(postdata)
    pg=urlopen(req)
    text=pg.read()
    pass
finally:
    flds1 = [ ('q', x1),('format','xml'),('authcode',authcode)]
    postdata = urlencode(flds1)
    req.add_data(postdata)
    pg=urlopen(req)
    text=pg.read()

src/r/d/Rdbhdb-HEAD/examples/ex4.py   Rdbhdb(Download)
# Direct connection; Not through API; Creates table test and then deletes it.
 
from urllib import urlencode
from urllib2 import Request, urlopen
 
url = 'http://rdbhost.com/db/'+'s000015'
authcode = 'KF7IUQPlwfSth4sBvjdqqanHkojAZzEjMshrkfEV0O53yz6w6v'
req = Request(url)
flds0 = [('authcode',authcode)]
postdata = urlencode(flds0)
);'''
q2 = "DROP TABLE test;"
flds1 = [ ('q', q1),('format','xml'),('authcode',authcode)]
postdata = urlencode(flds1)
req.add_data(postdata)
pg=urlopen(req)
text=pg.read()
print text
flds2 = [ ('q', q2),('format','xml'),('authcode',authcode)]
postdata = urlencode(flds2)

src/r/d/Rdbhdb-HEAD/examples/ex10.py   Rdbhdb(Download)
# Direct connection; Not through API; Prints rows of tables accounts and branches
 
from urllib import urlencode
from urllib2 import Request, urlopen
 
url = 'http://rdbhost.com/db/'+'s000015'
authcode = 'KF7IUQPlwfSth4sBvjdqqanHkojAZzEjMshrkfEV0O53yz6w6v'
req = Request(url)
print req
flds0 = [('authcode',authcode)]
postdata = urlencode(flds0)
req.add_data(postdata)
print req
flds1 = [ ('q', 'SELECT * FROM accounts'),('format','xml'),('authcode',authcode)]
postdata = urlencode(flds1)
req.add_data(postdata)
pg=urlopen(req)
text=pg.read()
print text
flds2 = [ ('q', 'SELECT * FROM branches'),('format','xml'),('authcode',authcode)]
postdata = urlencode(flds2)

src/r/d/Rdbhdb-HEAD/examples/get_no_table_rows.py   Rdbhdb(Download)
# Direct connection; Not through API; Prints rows of tables accounts and branches
 
from urllib import urlencode
from urllib2 import Request, urlopen
 
url = 'http://rdbhost.com/db/'+'s000015'
authcode = 'KF7IUQPlwfSth4sBvjdqqanHkojAZzEjMshrkfEV0O53yz6w6v'
req = Request(url)
flds0 = [('authcode',authcode)]
postdata = urlencode(flds0)
req.add_data(postdata)
q = "SELECT COUNT(*) FROM pg_type WHERE typtype = \'b\' "
flds1 = [ ('q', q),('format','xml'),('authcode',authcode)]
postdata = urlencode(flds1)
req.add_data(postdata)
pg=urlopen(req)
text=pg.read()

src/f/e/fepy-HEAD/example/gnosis_test.py   fepy(Download)
from urllib import urlencode, urlopen
from gnosis.xml.objectify import make_instance
 
key = 'bb3b53838b4f980367c230baf132958de15a98a9'
isbn = '059035342X'
query = dict(apikey=key, target='meta', q='', isbn=isbn)
url = 'http://apis.daum.net/search/book?' + urlencode(query)

src/r/d/Rdbhdb-HEAD/examples/ex9.py   Rdbhdb(Download)
# Testing Exception Raising. Direct connection (not through API)
from urllib import urlencode
from urllib2 import Request, urlopen
import json
 
def postit(url,fields):
    postdata = urlencode(fields)

src/t/r/tropo-webapi-python-HEAD/samples/itty_session_api.py   tropo-webapi-python(Download)
 
from itty import *
from tropo import Tropo, Session
from urllib import urlencode
from urllib2 import urlopen
 
@post('/index.json')
number = 'username@domain'	# change to the Jabber ID to which you want to send the message
message = 'hello from the session API!'
 
params = urlencode([('action', action), ('token', token), ('numberToDial', number), ('message', message)])
data = urlopen('%s?%s' % (base_url, params)).read()
 
run_itty(server='wsgiref', host='0.0.0.0', port=8888)

src/a/r/artie-HEAD/example/applications/weather.py   artie(Download)
from artie.applications import trigger
from artie.helpers import work_then_callback
 
from scrape import s
from urllib import urlencode
 
API_URL = \
'http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?%s'
 
def _weather(query):
    weather_url = API_URL % urlencode({'query': query})

src/d/j/django-datagrid-1.1/example/blogango/akismet.py   django-datagrid(Download)
 
 
import os, sys
from urllib import urlencode
 
import socket
if hasattr(socket, 'setdefaulttimeout'):
        # we *don't* trap the error here
        # so if akismet is down it will raise an HTTPError or URLError
        headers = {'User-Agent' : self.user_agent}
        resp = self._safeRequest(url, urlencode(data), headers)
        if resp.lower() == 'valid':
            return True
        else:
        # we *don't* trap the error here
        # so if akismet is down it will raise an HTTPError or URLError
        headers = {'User-Agent' : self.user_agent}
        resp = self._safeRequest(url, urlencode(data), headers)
        if DEBUG:
            return resp
        resp = resp.lower()
        # we *don't* trap the error here
        # so if akismet is down it will raise an HTTPError or URLError
        headers = {'User-Agent' : self.user_agent}
        self._safeRequest(url, urlencode(data), headers)
 
 
    def submit_ham(self, comment, data=None, build_data=True):
        # we *don't* trap the error here
        # so if akismet is down it will raise an HTTPError or URLError
        headers = {'User-Agent' : self.user_agent}
        self._safeRequest(url, urlencode(data), headers)
 

  1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9  Next