Commits

Lynn Rees committed 792896a

- httplet

Comments (0)

Files changed (6)

wire/http/httplet.py

+# -*- coding: utf-8 -*-
+'''wire httplet'''
+
+from callchain.root.chainlet import chainlet
+
+
+class httplet(chainlet):
+
+    def __init__(self, root):
+        super(httplet, self).__init__(root)
+        self._headers = root._headers
+        self._cookies = root._cookies
+        self._data = root._data

wire/http/request/client.py

 
 from wire.http.request.apps import apps
 from wire.http.request.keys.client import KRequestClient
+from collections import OrderedDict
 
 
 class Request(ResetTypeMixin):
         '''
         super(http, self).__init__(pattern, required, defaults, **kw)
         # files demand multipart as default otherwise go with urlencode
-        self._format = kw.get('format', self.defaults.format)
+        _setdefault = self._setdefault
+        _defaults = self.defaultss
+        _setdefault('_format', kw.get('format'), _defaults.format)
         # allow redirects
-        self._allow_redirects = kw.get(
-            'allow_redirects', self.defaults.allow_redirects,
-        )
+        _setdefault('_redirects', kw.get('redirects'), _defaults.redirects)
         # cert verification
-        self._verify = kw.get('verify', self.defaults.verify)
+        _setdefault('_verify', kw.get('verify'), _defaults.verify)
         # default timeout
-        self._timeout = kw.get('timeout', self.defaults.timeout)
+        _setdefault('_timeout', kw.get('timeout'), _defaults.timeout)
         # use random user agent
-        self._randomua = kw.pop('randomua', self.defaults.random_user_agent)
+        _setdefault('_randomua', kw.pop('randomua'), _defaults.random_ua)
         # authentication
-        self._auth = self.defaults.authentication
+        _setdefault('_auth', _defaults.authentication)
         # proxy
-        self._proxy = self.defaults.proxy
+        _setdefault('_proxy', _defaults.proxy)
+        # headers
+        self._headers = OrderedDict()
+        # cookies
+        self._cookies = None
 
     def __call__(self, *urls, **config):
         '''
         requester = self._requester
         pack = lambda x: lchain(requester, method, x.url, **x.args)
         with self._sync as sync:
-            exhaust(pack, sync.interable)
+            exhaust(pack(i) for i in sync.interable)
         self.commit()
         return self
+    
+    def clear(self):
+        '''clear all queues'''
+        self._resetdefaults()
+        self._qclear()
+        return self
 
     def get(self):
         '''
         @param server: proxy server
         @param host: proxy host
         '''
-        self._proxy = server, host
+        self._proxy = (server, host)
         return self

wire/http/request/cookie.py

 from functools import partial
 from Cookie import SimpleCookie, Morsel
 
+from stuf.utils import exhaustmap
+from twoq.support import isstring
+from appspace.keys import appifies
 
-class RequestCookie(SimpleCookie):
+from wire.http.httplet import httplet
+from wire.http.request.keys.header import KRequestCookie
+
+
+class Cookie(SimpleCookie):
 
     '''HTTP request specific cookie'''
 
-    def __init__(self, inpt=None):
-        super(RequestCookie, self).__init__()
+    def __init__(self, inpt=False):
+        super(Cookie, self).__init__()
         if inpt:
             self.load(input)
 
         rval, cval = self.value_encode(value)
         self._set(key, rval, cval)
 
-    def __iter__(self):
-        return iter(list(
-            tuple(i.split(': ')) for i in str(self).splitlines())
-        )
-
-    def __str__(self):
-        return self.dumps
-
     def _set(self, k, real_value, coded_value):
         m = self.get(k, Morsel())
         m.set(k, real_value, coded_value)
         dict.__setitem__(self, k, m)
 
+    def set(self, key, field, value):
+        m = self.get(key, Morsel())
+        if key.lower() in m._reserved:
+            m[field] = _cook._unquote(value)
+        else:
+            real_value, coded_value = self.value_decode(value)
+            m.set(field, real_value, coded_value)
+        dict.__setitem__(self, key, m)
+
     def _parse(self, cookie, patt=_cook._CookiePattern):
         i = 0  # Our starting point
         n = len(cookie)  # Length of string
         m = None  # current morsel
         unquote = _cook._unquote
         reserved = Morsel._reserved
+        value_decode = self.value_decode
+        setter = self._set
+        this = self
         while 0 <= i < n:
             # Start looking for a cookie
             match = patt.search(cookie, i)
                 if m:
                     m._morsel[k] = unquote(v)
             else:
-                rval, cval = self.value_decode(v)
-                self._set(k, rval, cval)
-                m = self[k]
+                rval, cval = value_decode(v)
+                setter(k, rval, cval)
+                m = this[k]
 
     def loads(self, data):
-        if isinstance(data, str):
+        if isstring(data):
             self._parse(data)
         else:
-            for k, v in data.iteritems():
-                self.__setitem__(k, v)
+            exhaustmap(data, self.__setitem__)
 
     def dumps(self):
-        return partial(super(RequestCookie, self).output, header='cookie:')
+        return partial(self.output, header='cookie:')
+
+
+@appifies(KRequestCookie)
+class RequestCookie(httplet):
+
+    '''request cookie manager'''
+
+    def __init__(self, root):
+        '''
+        init
+
+        @param root: root object
+        '''
+        super(RequestCookie, self).__init__(root)
+        # initialize cookies
+        self._cookies = self._synchback(
+            '_cookies', Cookie() if self._cookies is None else self._cookies,
+        )
+
+    def cookie(self, key, **values):
+        '''
+        *COOKIE* HTTP header
+
+        @param key: cookie key
+        @param **values: HTTP header values
+        '''
+        setr = self._cookies.set
+        exhaustmap(values, lambda x, y: setr(key, x, y))
+        return self
+
+    def back(self):
+        '''revert to root chain'''
+        # synchronize all requests with cookies
+        self.root.args(self._cookies).invoke('cookies')
+        return self._rback()

wire/http/request/keys/header.py

 '''http request keys'''
 
 from appspace.keys import AppspaceKey
+
+
+class KRequestCookie(AppspaceKey):
+    
+    '''HTTP request cookie setter'''
+
+    def cookie(key, **values):
+        '''
+        *COOKIE* HTTP header
+        
+        @param value: HTTP header value
+        '''
         
         
 class KRequestHeaders(AppspaceKey):
         
         @param value: HTTP header value
         '''
-        
-    def cookie(key, **values):
-        '''
-        *COOKIE* HTTP header
-        
-        @param value: HTTP header value
-        '''
     
     def connection(value):
         '''

wire/talk/multipartw.py

 '''multipart <-> Python talk'''
 
 from operator import setitem
-from itertools import starmap
 from StringIO import StringIO
 from cgi import parse_multipart
 
-from stuf.six import items
-from stuf.utils import exhaust
-from appspace.keys import appifies, ifilter
+from stuf.utils import exhaustmap
+from appspace.keys import appifies
 from callchain.mixin.reset import ResetLocalMixin
 from urllib3.filepost import encode_multipart_formdata
 
 
     @staticmethod
     def loads(data):
-        qdict = parse_multipart(
-            StringIO(data), dict(boundary='----------AaB03x'),
-        )
-        exhaust(starmap(
-            lambda x, y: setitem(x, y[0]),
-            ifilter(lambda x: len(x[1]) == 1, items(qdict))
-        ))
-        return qdict
+        q = parse_multipart(StringIO(data), dict(boundary='----------AaB03x'))
+        exhaustmap(q, lambda x, y: setitem(x, y[0]), lambda x: len(x[1]) == 1)
+        return q
 
 
 @appifies(KMultiPartDumps)

wire/talk/urlw.py

 
 import urllib
 from operator import setitem
-from itertools import starmap
 try:
     from urlparse import parse_qs
 except ImportError:
     from cgi import parse_qs
 
-from stuf.six import items
-from stuf.utils import exhaust
-from appspace.keys import appifies, ifilter
+from stuf.utils import exhaustmap
+from appspace.keys import appifies
 from callchain.mixin.reset import ResetLocalMixin
 
 from wire.talk.keys import KUrlEncodeDumps, KUrlEncodeLoads
 
     @staticmethod
     def loads(data, **kw):
-        qdict = parse_qs(data, **kw)
-        exhaust(starmap(
-            lambda x, y: setitem(x, y[0]),
-            ifilter(lambda x: len(x[1]) == 1, items(qdict))
-        ))
-        return qdict
+        q = parse_qs(data, **kw)
+        exhaustmap(q, lambda x, y: setitem(x, y[0]), lambda x: len(x[1]) == 1)
+        return q
 
 
 @appifies(KUrlEncodeDumps)