query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
create cookie
python
def create_cookie( key: str, value: str='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[Union[int, float, datetime]]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> SimpleCookie: """Create a Cookie given the options set The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code. """ cookie = SimpleCookie() cookie[key] = value cookie[key]['path'] = path cookie[key]['httponly'] = httponly # type: ignore cookie[key]['secure'] = secure # type: ignore if isinstance(max_age, timedelta): cookie[key]['max-age'] = f"{max_age.total_seconds():d}" if isinstance(max_age, int): cookie[key]['max-age'] = str(max_age) if expires is not None and isinstance(expires, (int, float)): cookie[key]['expires'] = format_date_time(int(expires)) elif expires is not None and isinstance(expires, datetime): cookie[key]['expires'] = format_date_time(expires.replace(tzinfo=timezone.utc).timestamp()) if domain is not None: cookie[key]['domain'] = domain return cookie
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/utils.py#L29-L59
create cookie
python
def create_cookie(host, path, secure, expires, name, value): """Shortcut function to create a cookie """ return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path, True, secure, expires, False, None, None, {})
https://github.com/borisbabic/browser_cookie3/blob/e695777c54509c286991c5bb5ca65f043d748f55/__init__.py#L274-L278
create cookie
python
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = dict( version=0, name=name, value=value, port=None, domain='', path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,) badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return Cookie(**result)
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L396-L425
create cookie
python
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result)
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L441-L474
create cookie
python
def create_cookie(name, value, domain, httponly=None, **kwargs): """Creates `cookielib.Cookie` instance""" if domain == 'localhost': domain = '' config = dict( name=name, value=value, version=0, port=None, domain=domain, path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rfc2109=False, rest={'HttpOnly': httponly}, ) for key in kwargs: if key not in config: raise GrabMisuseError('Function `create_cookie` does not accept ' '`%s` argument' % key) config.update(**kwargs) config['rest']['HttpOnly'] = httponly config['port_specified'] = bool(config['port']) config['domain_specified'] = bool(config['domain']) config['domain_initial_dot'] = (config['domain'] or '').startswith('.') config['path_specified'] = bool(config['path']) return Cookie(**config)
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L118-L152
create cookie
python
def set_cookie(self, name: str, value: str, *, expires: Optional[str]=None, domain: Optional[str]=None, max_age: Optional[Union[int, str]]=None, path: str='/', secure: Optional[str]=None, httponly: Optional[str]=None, version: Optional[str]=None) -> None: """Set or update response cookie. Sets new cookie or updates existent with new value. Also updates only those params which are not None. """ old = self._cookies.get(name) if old is not None and old.coded_value == '': # deleted cookie self._cookies.pop(name, None) self._cookies[name] = value c = self._cookies[name] if expires is not None: c['expires'] = expires elif c.get('expires') == 'Thu, 01 Jan 1970 00:00:00 GMT': del c['expires'] if domain is not None: c['domain'] = domain if max_age is not None: c['max-age'] = str(max_age) elif 'max-age' in c: del c['max-age'] c['path'] = path if secure is not None: c['secure'] = secure if httponly is not None: c['httponly'] = httponly if version is not None: c['version'] = version
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_response.py#L179-L221
create cookie
python
def set_cookie( # type: ignore self, key: str, value: AnyStr='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[datetime]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> None: """Set a cookie in the response headers. The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code. """ if isinstance(value, bytes): value = value.decode() # type: ignore cookie = create_cookie(key, value, max_age, expires, path, domain, secure, httponly) # type: ignore # noqa: E501 self.headers.add('Set-Cookie', cookie.output(header=''))
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L341-L360
create cookie
python
def create_cookie(self, delete=None): """ Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``. """ value = 'deleted' if delete else self._serialize(self.data) split_url = parse.urlsplit(self.adapter.url) domain = split_url.netloc.split(':')[0] # Work-around for issue #11, failure of WebKit-based browsers to accept # cookies set as part of a redirect response in some circumstances. if '.' not in domain: template = '{name}={value}; Path={path}; HttpOnly{secure}{expires}' else: template = ('{name}={value}; Domain={domain}; Path={path}; ' 'HttpOnly{secure}{expires}') return template.format( name=self.name, value=value, domain=domain, path=split_url.path, secure='; Secure' if self.secure else '', expires='; Expires=Thu, 01-Jan-1970 00:00:01 GMT' if delete else '' )
https://github.com/authomatic/authomatic/blob/90a9ce60cc405ae8a2bf5c3713acd5d78579a04e/authomatic/core.py#L364-L392
create cookie
python
def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): """Sets a cookie. The parameters are the same as in the cookie `Morsel` object in the Python standard library but it accepts unicode data, too. A warning is raised if the size of the cookie header exceeds :attr:`max_cookie_size`, but the header will still be set. :param key: the key (name) of the cookie to be set. :param value: the value of the cookie. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. :param expires: should be a `datetime` object or UNIX timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: If `True`, the cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are "same-site". """ self.headers.add( "Set-Cookie", dump_cookie( key, value=value, max_age=max_age, expires=expires, path=path, domain=domain, secure=secure, httponly=httponly, charset=self.charset, max_size=self.max_cookie_size, samesite=samesite, ), )
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L429-L483
create cookie
python
def set_cookie( self, name: str, value: Union[str, bytes], domain: str = None, expires: Union[float, Tuple, datetime.datetime] = None, path: str = "/", expires_days: int = None, **kwargs: Any ) -> None: """Sets an outgoing cookie name/value with the given options. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes. """ # The cookie library only accepts type str, in both python 2 and 3 name = escape.native_str(name) value = escape.native_str(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookie"): self._new_cookie = http.cookies.SimpleCookie() if name in self._new_cookie: del self._new_cookie[name] self._new_cookie[name] = value morsel = self._new_cookie[name] if domain: morsel["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: morsel["expires"] = httputil.format_timestamp(expires) if path: morsel["path"] = path for k, v in kwargs.items(): if k == "max_age": k = "max-age" # skip falsy values for httponly and secure flags because # SimpleCookie sets them regardless if k in ["httponly", "secure"] and not v: continue morsel[k] = v
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L596-L649
create cookie
python
def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp=""): """ Create and return a cookie :param name: Cookie name :param load: Cookie load :param seed: A seed for the HMAC function :param expire: Number of minutes before this cookie goes stale :param domain: The domain of the cookie :param path: The path specification for the cookie :return: A tuple to be added to headers """ cookie = SimpleCookie() if not timestamp: timestamp = str(int(time.mktime(time.gmtime()))) signature = cookie_signature(seed, load, timestamp) cookie[name] = "|".join([load, timestamp, signature]) if path: cookie[name]["path"] = path if domain: cookie[name]["domain"] = domain if expire: cookie[name]["expires"] = _expiration(expire, "%a, %d-%b-%Y %H:%M:%S GMT") return tuple(cookie.output().split(": ", 1))
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httputil.py#L320-L346
create cookie
python
def cookies(self): """Cookies in dict""" c = Cookie.SimpleCookie(self.getheader('set-cookie')) return dict((i.key, i.value) for i in c.values())
https://github.com/ifduyue/urlfetch/blob/e0ea4673367c157eb832ba4ba2635306c81a61be/urlfetch.py#L353-L356
create cookie
python
def set_cookie(self, key, value, domain=None, path='/', secure=False, httponly=True): """Set a cookie. Args: key (:obj:`str`): Cookie name value (:obj:`str`): Cookie value domain (:obj:`str`): Cookie domain path (:obj:`str`): Cookie value secure (:obj:`bool`): True if secure, False otherwise httponly (:obj:`bool`): True if it's a HTTP only cookie, False otherwise """ self._cookies[key] = value if domain: self._cookies[key]['domain'] = domain if path: self._cookies[key]['path'] = path if secure: self._cookies[key]['secure'] = secure if httponly: self._cookies[key]['httponly'] = httponly
https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L51-L72
create cookie
python
def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options): """ Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that are supported by :class:`cookie.Morsel`, including: :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (default: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: current path) :param secure: limit the cookie to HTTPS connections (default: off). :param httponly: prevents client-side javascript to read this cookie (default: off, requires Python 2.6 or newer). :param same_site: disables third-party use for a cookie. Allowed attributes: `lax` and `strict`. In strict mode the cookie will never be sent. In lax mode the cookie is only sent with a top-level GET request. If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Pickle is a potentially dangerous format. If an attacker gains access to the secret key, he could forge cookies that execute code on server side if unpickeld. Using pickle is discouraged and support for it will be removed in later versions of bottle. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side. """ if not self._cookies: self._cookies = SimpleCookie() # To add "SameSite" cookie support. Morsel._reserved['same-site'] = 'SameSite' if secret: if not isinstance(value, basestring): depr(0, 13, "Pickling of arbitrary objects into cookies is " "deprecated.", "Only store strings in cookies. " "JSON strings are fine, too.") encoded = base64.b64encode(pickle.dumps([name, value], -1)) sig = base64.b64encode(hmac.new(tob(secret), encoded, digestmod=digestmod).digest()) value = touni(tob('!') + sig + tob('?') + encoded) elif not isinstance(value, basestring): raise TypeError('Secret key required for non-string cookies.') # Cookie size plus options must not exceed 4kb. if len(name) + len(value) > 3800: raise ValueError('Content does not fit into a cookie.') self._cookies[name] = value for key, value in options.items(): if key == 'max_age': if isinstance(value, timedelta): value = value.seconds + value.days * 24 * 3600 if key == 'expires': if isinstance(value, (datedate, datetime)): value = value.timetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) # check values for SameSite cookie, because it's not natively supported by http.cookies. if key == 'same_site' and value.lower() not in ('lax', 'strict'): raise CookieError("Invalid attribute %r" % (key,)) if key in ('secure', 'httponly') and not value: continue self._cookies[name][key.replace('_', '-')] = value
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1797-L1878
create cookie
python
def set_cookie(self, key, value, **kargs): """ Add a new cookie with various options. If the cookie value is not a string, a secure cookie is created. Possible options are: expires, path, comment, domain, max_age, secure, version, httponly See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details """ if not isinstance(value, basestring): sec = self.app.config['securecookie.key'] value = cookie_encode(value, sec).decode('ascii') #2to3 hack self.COOKIES[key] = value for k, v in kargs.iteritems(): self.COOKIES[key][k.replace('_', '-')] = v
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle2.py#L809-L823
create cookie
python
def dump_cookie( key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, charset="utf-8", sync_expires=True, max_size=4093, samesite=None, ): """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too. On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. In both cases the return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. If a unicode string is returned it's tunneled through latin1 as required by PEP 3333. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for unicode values. :param sync_expires: automatically set expires if max_age is defined but expires not. :param max_size: Warn if the final header value exceeds this size. The default, 4093, should be safely `supported by most browsers <cookie_>`_. Set to 0 to disable this check. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are "same-site". .. _`cookie`: http://browsercookielimits.squawky.net/ """ key = to_bytes(key, charset) value = to_bytes(value, charset) if path is not None: path = iri_to_uri(path, charset) domain = _make_cookie_domain(domain) if isinstance(max_age, timedelta): max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds if expires is not None: if not isinstance(expires, string_types): expires = cookie_date(expires) elif max_age is not None and sync_expires: expires = to_bytes(cookie_date(time() + max_age)) samesite = samesite.title() if samesite else None if samesite not in ("Strict", "Lax", None): raise ValueError("invalid SameSite value; must be 'Strict', 'Lax' or None") buf = [key + b"=" + _cookie_quote(value)] # XXX: In theory all of these parameters that are not marked with `None` # should be quoted. Because stdlib did not quote it before I did not # want to introduce quoting there now. for k, v, q in ( (b"Domain", domain, True), (b"Expires", expires, False), (b"Max-Age", max_age, False), (b"Secure", secure, None), (b"HttpOnly", httponly, None), (b"Path", path, False), (b"SameSite", samesite, False), ): if q is None: if v: buf.append(k) continue if v is None: continue tmp = bytearray(k) if not isinstance(v, (bytes, bytearray)): v = to_bytes(text_type(v), charset) if q: v = _cookie_quote(v) tmp += b"=" + v buf.append(bytes(tmp)) # The return value will be an incorrectly encoded latin1 header on # Python 3 for consistency with the headers object and a bytestring # on Python 2 because that's how the API makes more sense. rv = b"; ".join(buf) if not PY2: rv = rv.decode("latin1") # Warn if the final value of the cookie is less than the limit. If the # cookie is too large, then it may be silently ignored, which can be quite # hard to debug. cookie_size = len(rv) if max_size and cookie_size > max_size: value_size = len(value) warnings.warn( 'The "{key}" cookie is too large: the value was {value_size} bytes' " but the header required {extra_size} extra bytes. The final size" " was {cookie_size} bytes but the limit is {max_size} bytes." " Browsers may silently ignore cookies larger than this.".format( key=key, value_size=value_size, extra_size=cookie_size - value_size, cookie_size=cookie_size, max_size=max_size, ), stacklevel=2, ) return rv
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L1086-L1219
create cookie
python
def set_cookie(self, name, value, secret=None, **options): ''' Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that are supported by :class:`cookie.Morsel`, including: :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (default: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: current path) :param secure: limit the cookie to HTTPS connections (default: off). :param httponly: prevents client-side javascript to read this cookie (default: off, requires Python 2.6 or newer). If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side. ''' if not self._cookies: self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((name, value), secret)) elif not isinstance(value, basestring): raise TypeError('Secret key missing for non-string Cookie.') if len(value) > 4096: raise ValueError('Cookie value to long.') self._cookies[name] = value for key, value in options.items(): if key == 'max_age': if isinstance(value, timedelta): value = value.seconds + value.days * 24 * 3600 if key == 'expires': if isinstance(value, (datedate, datetime)): value = value.timetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value) self._cookies[name][key.replace('_', '-')] = value
https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1579-L1633
create cookie
python
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): """Sets a cookie. The parameters are the same as in the cookie `Morsel` object in the Python standard library but it accepts unicode data, too. :param key: the key (name) of the cookie to be set. :param value: the value of the cookie. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. :param expires: should be a `datetime` object or UNIX timestamp. :param domain: if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param path: limits the cookie to a given path, per default it will span the whole domain. """ self.headers.add('Set-Cookie', dump_cookie(key, value, max_age, expires, path, domain, secure, httponly, self.charset))
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L939-L960
create cookie
python
def cookie( url, name, value, expires=None): '''Return a new Cookie using a slightly more friendly API than that provided by six.moves.http_cookiejar @param name The cookie name {str} @param value The cookie value {str} @param url The URL path of the cookie {str} @param expires The expiry time of the cookie {datetime}. If provided, it must be a naive timestamp in UTC. ''' u = urlparse(url) domain = u.hostname if '.' not in domain and not _is_ip_addr(domain): domain += ".local" port = str(u.port) if u.port is not None else None secure = u.scheme == 'https' if expires is not None: if expires.tzinfo is not None: raise ValueError('Cookie expiration must be a naive datetime') expires = (expires - datetime(1970, 1, 1)).total_seconds() return http_cookiejar.Cookie( version=0, name=name, value=value, port=port, port_specified=port is not None, domain=domain, domain_specified=True, domain_initial_dot=False, path=u.path, path_specified=True, secure=secure, expires=expires, discard=False, comment=None, comment_url=None, rest=None, rfc2109=False, )
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/_utils/__init__.py#L123-L165
create cookie
python
def set_cookie(self, key, value, **kargs): """ Add a new cookie with various options. If the cookie value is not a string, a secure cookie is created. Possible options are: expires, path, comment, domain, max_age, secure, version, httponly See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details """ if not isinstance(value, str): sec = self.app.config['securecookie.key'] value = cookie_encode(value, sec).decode('ascii') #2to3 hack self.COOKIES[key] = value for k, v in kargs.items(): self.COOKIES[key][k.replace('_', '-')] = v
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py#L809-L823
create cookie
python
def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=False, httponly=False, expires=None): """Set a response cookie. Parameters: key : The cookie name. value : The cookie value. max_age : The maximum age of the cookie in seconds, or as a datetime.timedelta object. path : Restrict the cookie to this path (default: '/'). domain : Restrict the cookie to his domain. secure : When True, instruct the client to only sent the cookie over HTTPS. httponly : When True, instruct the client to disallow javascript access to the cookie. expires : Another way of specifying the maximum age of the cookie. Accepts the same values as max_age (number of seconds, datetime.timedelta). Additionaly accepts a datetime.datetime object. Note: a value of type int or float is interpreted as a number of seconds in the future, *not* as Unix timestamp. """ key, value = key.encode('utf-8'), value.encode('utf-8') cookie = SimpleCookie({key: value}) m = cookie[key] if max_age is not None: if isinstance(max_age, timedelta): m['max-age'] = int(total_seconds(max_age)) else: m['max-age'] = int(max_age) if path is not None: m['path'] = path.encode('utf-8') if domain is not None: m['domain'] = domain.encode('utf-8') if secure: m['secure'] = True if httponly: m['httponly'] = True if expires is not None: # 'expires' expects an offset in seconds, like max-age if isinstance(expires, datetime): expires = total_seconds(expires - datetime.utcnow()) elif isinstance(expires, timedelta): expires = total_seconds(expires) m['expires'] = int(expires) self.headers.add_header('Set-Cookie', m.OutputString())
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/response.py#L210-L259
create cookie
python
def cookie(self, value): """ Set cookie. :param value: """ if value and not value.is_empty(): self._cookie = value else: self._cookie = Cookie()
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L316-L324
create cookie
python
def set_cookie(cookies, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): '''Set a cookie key into the cookies dictionary *cookies*.''' cookies[key] = value if expires is not None: if isinstance(expires, datetime): now = (expires.now(expires.tzinfo) if expires.tzinfo else expires.utcnow()) delta = expires - now # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta = delta + timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None max_age = max(0, delta.days * 86400 + delta.seconds) else: cookies[key]['expires'] = expires if max_age is not None: cookies[key]['max-age'] = max_age # IE requires expires, so set it if hasn't been already. if not expires: cookies[key]['expires'] = http_date(time.time() + max_age) if path is not None: cookies[key]['path'] = path if domain is not None: cookies[key]['domain'] = domain if secure: cookies[key]['secure'] = True if httponly: cookies[key]['httponly'] = True
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/wsgiresponse.py#L246-L276
create cookie
python
def make_cookies(self, response, request): """Return sequence of Cookie objects extracted from response object.""" # get cookie-attributes for RFC 2965 and Netscape protocols headers = response.info() rfc2965_hdrs = headers.get_all("Set-Cookie2", []) ns_hdrs = headers.get_all("Set-Cookie", []) rfc2965 = self._policy.rfc2965 netscape = self._policy.netscape if ((not rfc2965_hdrs and not ns_hdrs) or (not ns_hdrs and not rfc2965) or (not rfc2965_hdrs and not netscape) or (not netscape and not rfc2965)): return [] # no relevant cookie headers: quick exit try: cookies = self._cookies_from_attrs_set( split_header_words(rfc2965_hdrs), request) except Exception: _warn_unhandled_exception() cookies = [] if ns_hdrs and netscape: try: # RFC 2109 and Netscape cookies ns_cookies = self._cookies_from_attrs_set( parse_ns_headers(ns_hdrs), request) except Exception: _warn_unhandled_exception() ns_cookies = [] self._process_rfc2109_cookies(ns_cookies) # Look for Netscape cookies (from Set-Cookie headers) that match # corresponding RFC 2965 cookies (from Set-Cookie2 headers). # For each match, keep the RFC 2965 cookie and ignore the Netscape # cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are # bundled in with the Netscape cookies for this purpose, which is # reasonable behaviour. if rfc2965: lookup = {} for cookie in cookies: lookup[(cookie.domain, cookie.path, cookie.name)] = None def no_matching_rfc2965(ns_cookie, lookup=lookup): key = ns_cookie.domain, ns_cookie.path, ns_cookie.name return key not in lookup ns_cookies = filter(no_matching_rfc2965, ns_cookies) if ns_cookies: cookies.extend(ns_cookies) return cookies
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1577-L1629
create cookie
python
def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ assert self.cookie_monster, 'Cookie Monster not set' #, domain=domain, path=path) self.cookie_monster.set_cookie(name, value)
https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/auth.py#L221-L232
create cookie
python
def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/models.py#L556-L574
create cookie
python
def cookie(self, k, v, expires=None, domain=None, path='/', secure=False): """ Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param expires: Cookie expiration date :param domain: Cookie domain :param path: Cookie path :param secure: Flag for `https only` :type k: str :type v: str :type expires: datetime.datetime :type domain: str :type path: str :type secure: bool """ ls = ['{}={}'.format(k, v)] if expires is not None: dt = format_date_time(mktime(expires.timetuple())) ls.append('expires={}'.format(dt)) if domain is not None: ls.append('domain={}'.format(domain)) if path is not None: ls.append('path={}'.format(path)) if secure: ls.append('secure') return self.header('Set-Cookie', '; '.join(ls), False)
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/response.py#L85-L116
create cookie
python
def set_cookie(self, kaka, request): """Returns a http_cookiejar.Cookie based on a set-cookie header line""" if not kaka: return part = urlparse(request.url) _domain = part.hostname logger.debug("%s: '%s'", _domain, kaka) for cookie_name, morsel in kaka.items(): std_attr = ATTRS.copy() std_attr["name"] = cookie_name _tmp = morsel.coded_value if _tmp.startswith('"') and _tmp.endswith('"'): std_attr["value"] = _tmp[1:-1] else: std_attr["value"] = _tmp std_attr["version"] = 0 # copy attributes that have values for attr in morsel.keys(): if attr in ATTRS: if morsel[attr]: if attr == "expires": std_attr[attr] = _since_epoch(morsel[attr]) elif attr == "path": if morsel[attr].endswith(","): std_attr[attr] = morsel[attr][:-1] else: std_attr[attr] = morsel[attr] else: std_attr[attr] = morsel[attr] elif attr == "max-age": if morsel["max-age"]: std_attr["expires"] = time.time() + int(morsel["max-age"]) for att, item in PAIRS.items(): if std_attr[att]: std_attr[item] = True if std_attr["domain"]: if std_attr["domain"].startswith("."): std_attr["domain_initial_dot"] = True else: std_attr["domain"] = _domain std_attr["domain_specified"] = True if morsel["max-age"] is 0: try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass elif std_attr["expires"] and std_attr["expires"] < utc_now(): try: self.cookiejar.clear(domain=std_attr["domain"], path=std_attr["path"], name=std_attr["name"]) except ValueError: pass else: new_cookie = http_cookiejar.Cookie(**std_attr) self.cookiejar.set_cookie(new_cookie)
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L151-L215
create cookie
python
def set_cookie(name, value): """Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/plain responses: 200: description: Set cookies and redirects to cookie list. """ r = app.make_response(redirect(url_for("view_cookies"))) r.set_cookie(key=name, value=value, secure=secure_cookie()) return r
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L857-L879
create cookie
python
def append_cookie(self, cookie, name, payload, typ, domain=None, path=None, timestamp="", max_age=0): """ Adds a cookie to a SimpleCookie instance :param cookie: :param name: :param payload: :param typ: :param domain: :param path: :param timestamp: :param max_age: :return: """ timestamp = str(int(time.time())) # create cookie payload try: _payload = "::".join([payload, timestamp, typ]) except TypeError: _payload = "::".join([payload[0], timestamp, typ]) content = make_cookie_content(name, _payload, self.sign_key, domain=domain, path=path, timestamp=timestamp, enc_key=self.enc_key, max_age=max_age, sign_alg=self.sign_alg) for name, args in content.items(): cookie[name] = args['value'] for key, value in args.items(): if key == 'value': continue cookie[name][key] = value return cookie
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/cookie.py#L369-L404
create cookie
python
def set_cookie(self, name, value, attrs={}): """Add a Set-Cookie header to response object. For a description about cookie attribute values, see https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel. Arguments: name (str): Name of the cookie value (str): Value of the cookie attrs (dict): Dicitionary with cookie attribute keys and values. """ cookie = http.cookies.SimpleCookie() cookie[name] = value for key, value in attrs.items(): cookie[name][key] = value self.add_header('Set-Cookie', cookie[name].OutputString())
https://github.com/susam/ice/blob/532e685c504ea96f9e42833594585159ac1d2068/ice.py#L794-L810
create cookie
python
def set_cookie(self, key, value, secret=None, **kargs): ''' Add a cookie or overwrite an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param key: the name of the cookie. :param value: the value of the cookie. :param secret: required for signed cookies. (default: None) :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (defaut: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: /) If neither `expires` nor `max_age` are set (default), the cookie lasts only as long as the browser is not closed. Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side. ''' if secret: value = touni(cookie_encode((key, value), secret)) elif not isinstance(value, six.string_types): raise TypeError('Secret missing for non-string Cookie.') self.COOKIES[key] = value for k, v in six.iteritems(kargs): self.COOKIES[key][k.replace('_', '-')] = v
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1076-L1108
create cookie
python
def cookie_signature(seed, *parts): """Generates a cookie signature.""" sha1 = hmac.new(seed, digestmod=hashlib.sha1) for part in parts: if part: sha1.update(part) return sha1.hexdigest()
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httputil.py#L311-L317
create cookie
python
def cookies(self, url): """ Return cookies that are matching the path and are still valid :param url: :return: """ part = urlparse(url) #if part.port: # _domain = "%s:%s" % (part.hostname, part.port) #else: _domain = part.hostname cookie_dict = {} now = utc_now() for _, a in list(self.cookiejar._cookies.items()): for _, b in a.items(): for cookie in list(b.values()): # print(cookie) if cookie.expires and cookie.expires <= now: continue if not re.search("%s$" % cookie.domain, _domain): continue if not re.match(cookie.path, part.path): continue cookie_dict[cookie.name] = cookie.value return cookie_dict
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L120-L149
create cookie
python
def set_cookies(): """Sets cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string style: form produces: - text/plain responses: 200: description: Redirect to cookie list """ cookies = dict(request.args.items()) r = app.make_response(redirect(url_for("view_cookies"))) for key, value in cookies.items(): r.set_cookie(key=key, value=value, secure=secure_cookie()) return r
https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L883-L910
create cookie
python
def _get_cookie(self, mgmt_ip, config, refresh=False): """Performs authentication and retries cookie.""" if mgmt_ip not in self.credentials: return None security_data = self.credentials[mgmt_ip] verify = security_data[const.HTTPS_CERT_TUPLE] if not verify: verify = security_data[const.HTTPS_VERIFY_TUPLE] if not refresh and security_data[const.COOKIE_TUPLE]: return security_data[const.COOKIE_TUPLE], verify payload = {"aaaUser": {"attributes": { "name": security_data[const.UNAME_TUPLE], "pwd": security_data[const.PW_TUPLE]}}} headers = {"Content-type": "application/json", "Accept": "text/plain"} url = "{0}://{1}/api/aaaLogin.json".format(DEFAULT_SCHEME, mgmt_ip) try: response = self.session.request('POST', url, data=jsonutils.dumps(payload), headers=headers, verify=verify, timeout=self.timeout * 2) except Exception as e: raise cexc.NexusConnectFailed(nexus_host=mgmt_ip, exc=e) self.status = response.status_code if response.status_code == requests.codes.OK: cookie = response.headers.get('Set-Cookie') security_data = ( security_data[const.UNAME_TUPLE:const.COOKIE_TUPLE] + (cookie,)) self.credentials[mgmt_ip] = security_data return cookie, verify else: e = "REST API connect returned Error code: " e += str(self.status) raise cexc.NexusConnectFailed(nexus_host=mgmt_ip, exc=e)
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_client.py#L61-L105
create cookie
python
def dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True): """Creates a new Set-Cookie header without the ``Set-Cookie`` prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too. On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. In both cases the return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. If a unicode string is returned it's tunneled through latin1 as required by PEP 3333. The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys. :param max_age: should be a number of seconds, or `None` (default) if the cookie should last only as long as the client's browser session. Additionally `timedelta` objects are accepted, too. :param expires: should be a `datetime` object or unix timestamp. :param path: limits the cookie to a given path, per default it will span the whole domain. :param domain: Use this if you want to set a cross-domain cookie. For example, ``domain=".example.com"`` will set a cookie that is readable by the domain ``www.example.com``, ``foo.example.com`` etc. Otherwise, a cookie will only be readable by the domain that set it. :param secure: The cookie will only be available via HTTPS :param httponly: disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. :param charset: the encoding for unicode values. :param sync_expires: automatically set expires if max_age is defined but expires not. """ key = to_bytes(key, charset) value = to_bytes(value, charset) if path is not None: path = iri_to_uri(path, charset) domain = _make_cookie_domain(domain) if isinstance(max_age, timedelta): max_age = (max_age.days * 60 * 60 * 24) + max_age.seconds if expires is not None: if not isinstance(expires, string_types): expires = cookie_date(expires) elif max_age is not None and sync_expires: expires = to_bytes(cookie_date(time() + max_age)) buf = [key + b'=' + _cookie_quote(value)] # XXX: In theory all of these parameters that are not marked with `None` # should be quoted. Because stdlib did not quote it before I did not # want to introduce quoting there now. for k, v, q in ((b'Domain', domain, True), (b'Expires', expires, False,), (b'Max-Age', max_age, False), (b'Secure', secure, None), (b'HttpOnly', httponly, None), (b'Path', path, False)): if q is None: if v: buf.append(k) continue if v is None: continue tmp = bytearray(k) if not isinstance(v, (bytes, bytearray)): v = to_bytes(text_type(v), charset) if q: v = _cookie_quote(v) tmp += b'=' + v buf.append(bytes(tmp)) # The return value will be an incorrectly encoded latin1 header on # Python 3 for consistency with the headers object and a bytestring # on Python 2 because that's how the API makes more sense. rv = b'; '.join(buf) if not PY2: rv = rv.decode('latin1') return rv
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/http.py#L865-L951
create cookie
python
def add_cookie(self, key, value, **attrs): ''' Finer control over cookies. Allow specifying an Morsel arguments. ''' if attrs: c = Morsel() c.set(key, value, **attrs) self.cookies[key] = c else: self.cookies[key] = value
https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/response.py#L108-L117
create cookie
python
def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" c = self._cookies self._cookies_lock.acquire() try: if cookie.domain not in c: c[cookie.domain] = {} c2 = c[cookie.domain] if cookie.path not in c2: c2[cookie.path] = {} c3 = c2[cookie.path] c3[cookie.name] = cookie finally: self._cookies_lock.release()
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1644-L1655
create cookie
python
def cookies(self): """ Returns a list of all cookies in cookie string format. """ return [line.strip() for line in self.conn.issue_command("GetCookies").split("\n") if line.strip()]
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L301-L305
create cookie
python
def _build_cookie_jar(cls, session: AppSession): '''Build the cookie jar''' if not session.args.cookies: return if session.args.load_cookies or session.args.save_cookies: session.factory.set('CookieJar', BetterMozillaCookieJar) cookie_jar = session.factory.new('CookieJar') if session.args.load_cookies: cookie_jar.load(session.args.load_cookies, ignore_discard=True) else: cookie_jar = session.factory.new('CookieJar') policy = session.factory.new('CookiePolicy', cookie_jar=cookie_jar) cookie_jar.set_policy(policy) _logger.debug(__('Loaded cookies: {0}', list(cookie_jar))) cookie_jar_wrapper = session.factory.new( 'CookieJarWrapper', cookie_jar, save_filename=session.args.save_cookies, keep_session_cookies=session.args.keep_session_cookies, ) return cookie_jar_wrapper
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L180-L209
create cookie
python
def add_cookie(self, cookie_dict): """Set a cookie. Support: Web(WebView) Args: cookie_dict: A dictionary contain keys: "name", "value", ["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"]. Returns: WebElement Object. """ if not isinstance(cookie_dict, dict): raise TypeError('Type of the cookie must be a dict.') if not cookie_dict.get( 'name', None ) or not cookie_dict.get( 'value', None): raise KeyError('Missing required keys, \'name\' and \'value\' must be provided.') self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L634-L654
create cookie
python
def set_cookie(self, key, value, expiration='Infinity', path='/', domain='', secure=False): """ expiration (int): seconds after with the cookie automatically gets deleted """ secure = 'true' if secure else 'false' self.app_instance.execute_javascript(""" var sKey = "%(sKey)s"; var sValue = "%(sValue)s"; var vEnd = eval("%(vEnd)s"); var sPath = "%(sPath)s"; var sDomain = "%(sDomain)s"; var bSecure = %(bSecure)s; if( (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) == false ){ var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); } """%{'sKey': key, 'sValue': value, 'vEnd': expiration, 'sPath': path, 'sDomain': domain, 'bSecure': secure})
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/session_app.py#L73-L103
create cookie
python
def cookie_eater(ctx): """Eat cookies as they're baked.""" state = ctx.create_state() state["ready"] = True for _ in state.when_change("cookies"): eat_cookie(state)
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/examples/cookie_eater.py#L39-L45
create cookie
python
def _make_cookie(self): """ Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing. """ return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC, os.getpid(), id(self), thread.get_ident())
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L2158-L2165
create cookie
python
def cookies(self): """Request cookies :rtype: dict """ http_cookie = self.environ.get('HTTP_COOKIE', '') _cookies = { k: v.value for (k, v) in SimpleCookie(http_cookie).items() } return _cookies
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/http.py#L90-L100
create cookie
python
def del_cookie(self, name: str, *, domain: Optional[str]=None, path: str='/') -> None: """Delete cookie. Creates new empty expired cookie. """ # TODO: do we need domain/path here? self._cookies.pop(name, None) self.set_cookie(name, '', max_age=0, expires="Thu, 01 Jan 1970 00:00:00 GMT", domain=domain, path=path)
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_response.py#L223-L234
create cookie
python
def cookies(self): """Returns a dictionary mapping cookie names to their values.""" if self._cookies is None: c = SimpleCookie(self.environ.get('HTTP_COOKIE')) self._cookies = dict([ (k.decode('utf-8'), v.value.decode('utf-8')) for k, v in c.items() ]) return self._cookies
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L421-L429
create cookie
python
def cookie_is_encoded(data): ''' Verify and decode an encoded string. Return an object or None''' return bool(data.startswith(u'!'.encode('ascii')) and u'?'.encode('ascii') in data)
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle2.py#L1023-L1025
create cookie
python
def make_cookie_values(cj, class_name): """ Makes a string of cookie keys and values. Can be used to set a Cookie header. """ path = "/" + class_name cookies = [c.name + '=' + c.value for c in cj if c.domain == "class.coursera.org" and c.path == path] return '; '.join(cookies)
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L243-L255
create cookie
python
def create_cookies(self, file, need_captcha=False, use_getpass=True): """在终端中执行登录流程,将 cookies 存放在文件中以便后续使用 :param str file: 文件名 :param bool need_captcha: 登录过程中是否使用验证码, 默认为 False :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: """ cookies_str = self.login_in_terminal(need_captcha, use_getpass) if cookies_str: with open(file, 'w') as f: f.write(cookies_str) print('cookies file created.') else: print('can\'t create cookies.')
https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/client.py#L140-L155
create cookie
python
def use(self, cookies): """ 如果遭遇验证码,用这个接口 :type cookies: str|dict :param cookies: cookie字符串或者字典 :return: self """ self.cookies = dict([item.split('=', 1) for item in re.split(r'; *', cookies)]) \ if isinstance(cookies, str) else cookies self.flush() self.persist() return self
https://github.com/acrazing/dbapi/blob/8c1f85cb1a051daf7be1fc97a62c4499983e9898/dbapi/base.py#L230-L242
create cookie
python
def cookie(self): """ Cookie values. """ if self._cookie is None: self._cookie = self.arg_container() data = compat.parse_qs(self.http_header('cookie') or '') for k, v in data.items(): self._cookie[k.strip()] = v[0] return self._cookie
https://github.com/tomokinakamaru/mapletree/blob/19ec68769ef2c1cd2e4164ed8623e0c4280279bb/mapletree/defaults/request/request.py#L92-L102
create cookie
python
def from_string(cls, line, ignore_bad_cookies=False, ignore_bad_attributes=True): "Construct a Cookie object from a line of Set-Cookie header data." cookie_dict = parse_one_response( line, ignore_bad_cookies=ignore_bad_cookies, ignore_bad_attributes=ignore_bad_attributes) if not cookie_dict: return None return cls.from_dict( cookie_dict, ignore_bad_attributes=ignore_bad_attributes)
https://github.com/sashahart/cookies/blob/ab8185e06f221eaf65305f15e05852393723ac95/cookies.py#L778-L787
create cookie
python
def set_cookie(response, name, value, expiry_seconds=None, secure=False): """ Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded. """ if expiry_seconds is None: expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days. expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=expiry_seconds), "%a, %d-%b-%Y %H:%M:%S GMT") # Django doesn't seem to support unicode cookie keys correctly on # Python 2. Work around by encoding it. See # https://code.djangoproject.com/ticket/19802 try: response.set_cookie(name, value, expires=expires, secure=secure) except (KeyError, TypeError): response.set_cookie(name.encode('utf-8'), value, expires=expires, secure=secure)
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L183-L200
create cookie
python
def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values() if len(cookies) > self.MAX_PARAMS: raise HTTPError(413, 'Too many cookies') return FormsDict((c.key, c.value) for c in cookies)
https://github.com/klen/pyserve/blob/5942ff2eb41566fd39d73abbd3e5c7caa7366aa8/pyserve/bottle.py#L968-L974
create cookie
python
def cookie(data, key_salt='', secret=None, digestmod=None): """ Encodes or decodes a signed cookie. @data: cookie data @key_salt: HMAC key signing salt @secret: HMAC signing secret key @digestmod: hashing algorithm to sign with, recommended >=sha256 -> HMAC signed or unsigned cookie data .. from vital.security import cookie cookie("Hello, world.", "saltyDog", secret="alBVlwe") # -> '!YuOoKwDp8GhrwwojdjTxSCj1c2Z+7yz7r6cC7E3hBWo=?IkhlbGxvLCB3b3JsZC4i' cookie( "!YuOoKwDp8GhrwwojdjTxSCj1c2Z+7yz7r6cC7E3hBWo=?IkhlbGxvLCB3b3JsZC4i", "saltyDog", secret="alBVlwe") # -> 'Hello, world.' .. """ digestmod = digestmod or sha256 if not data: return None try: # Decode signed cookie assert cookie_is_encoded(data) datab = uniorbytes(data, bytes) sig, msg = datab.split(uniorbytes('?', bytes), 1) key = ("{}{}").format(secret, key_salt) sig_check = hmac.new( key=uniorbytes(key, bytes), msg=msg, digestmod=digestmod).digest() sig_check = uniorbytes(b64encode(sig_check), bytes) if lscmp(sig[1:], sig_check): return json.loads(uniorbytes(b64decode(msg))) return None except: # Encode and sign a json-able object. Return a string. key = ("{}{}").format(secret, key_salt) msg = b64encode(uniorbytes(json.dumps(data), bytes)) sig = hmac.new( key=uniorbytes(key, bytes), msg=msg, digestmod=digestmod).digest() sig = uniorbytes(b64encode(sig), bytes) return uniorbytes('!'.encode() + sig + '?'.encode() + msg)
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L179-L222
create cookie
python
def go_to_py_cookie(go_cookie): '''Convert a Go-style JSON-unmarshaled cookie into a Python cookie''' expires = None if go_cookie.get('Expires') is not None: t = pyrfc3339.parse(go_cookie['Expires']) expires = t.timestamp() return cookiejar.Cookie( version=0, name=go_cookie['Name'], value=go_cookie['Value'], port=None, port_specified=False, # Unfortunately Python cookies don't record the original # host that the cookie came from, so we'll just use Domain # for that purpose, and record that the domain was specified, # even though it probably was not. This means that # we won't correctly record the CanonicalHost entry # when writing the cookie file after reading it. domain=go_cookie['Domain'], domain_specified=not go_cookie['HostOnly'], domain_initial_dot=False, path=go_cookie['Path'], path_specified=True, secure=go_cookie['Secure'], expires=expires, discard=False, comment=None, comment_url=None, rest=None, rfc2109=False, )
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/gocookies.py#L45-L75
create cookie
python
def COOKIES(self): """ Cookie information parsed into a dictionary. Secure cookies are NOT decoded automatically. See Request.get_cookie() for details. """ if self._COOKIES is None: raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE','')) self._COOKIES = {} for cookie in raw_dict.itervalues(): self._COOKIES[cookie.key] = cookie.value return self._COOKIES
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle2.py#L740-L751
create cookie
python
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm( time.strptime(morsel['expires'], time_template) ) return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L477-L505
create cookie
python
def make_cookie_content(name, load, sign_key, domain=None, path=None, timestamp="", enc_key=None, max_age=0, sign_alg='SHA256'): """ Create and return a cookies content If you only provide a `seed`, a HMAC gets added to the cookies value and this is checked, when the cookie is parsed again. If you provide both `seed` and `enc_key`, the cookie gets protected by using AEAD encryption. This provides both a MAC over the whole cookie and encrypts the `load` in a single step. The `seed` and `enc_key` parameters should be byte strings of at least 16 bytes length each. Those are used as cryptographic keys. :param name: Cookie name :type name: text :param load: Cookie load :type load: text :param sign_key: A sign_key key for payload signing :type sign_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance :param domain: The domain of the cookie :param path: The path specification for the cookie :param timestamp: A time stamp :type timestamp: text :param enc_key: The key to use for payload encryption. :type enc_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance :param max_age: The time in seconds for when a cookie will be deleted :type max_age: int :return: A SimpleCookie instance """ if not timestamp: timestamp = str(int(time.time())) _cookie_value = sign_enc_payload(load, timestamp, sign_key=sign_key, enc_key=enc_key, sign_alg=sign_alg) content = {name: {"value": _cookie_value}} if path is not None: content[name]["path"] = path if domain is not None: content[name]["domain"] = domain content[name]['httponly'] = True if max_age: content[name]["expires"] = in_a_while(seconds=max_age) return content
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/cookie.py#L132-L181
create cookie
python
def add_cookie(self, cookie): """ Add new cookie (or replace if there is cookie with the same name already) :param cookie: cookie to add :return: None """ if self.__ro_flag: raise RuntimeError('Read-only cookie-jar changing attempt') self.__cookies[cookie.name()] = cookie
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L243-L251
create cookie
python
def set_cookie(self, cookie): ''' Add a cookie to the remote chromium instance. Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`. ''' # Function path: Network.setCookie # Domain: Network # Method name: setCookie # WARNING: This function is marked 'Experimental'! # Parameters: # Required arguments: # 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. # 'name' (type: string) -> The name of the cookie. # 'value' (type: string) -> The value of the cookie. # Optional arguments: # 'domain' (type: string) -> If omitted, the cookie becomes a host-only cookie. # 'path' (type: string) -> Defaults to the path portion of the url parameter. # 'secure' (type: boolean) -> Defaults ot false. # 'httpOnly' (type: boolean) -> Defaults to false. # 'sameSite' (type: CookieSameSite) -> Defaults to browser default behavior. # 'expirationDate' (type: Timestamp) -> If omitted, the cookie becomes a session cookie. # Returns: # 'success' (type: boolean) -> True if successfully set cookie. # Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. assert isinstance(cookie, http.cookiejar.Cookie), 'The value passed to `set_cookie` must be an instance of http.cookiejar.Cookie().' + \ ' Passed: %s ("%s").' % (type(cookie), cookie) # Yeah, the cookielib stores this attribute as a string, despite it containing a # boolean value. No idea why. is_http_only = str(cookie.get_nonstandard_attr('httponly', 'False')).lower() == "true" # I'm unclear what the "url" field is actually for. A cookie only needs the domain and # path component to be fully defined. Considering the API apparently allows the domain and # path parameters to be unset, I think it forms a partially redundant, with some # strange interactions with mode-changing between host-only and more general # cookies depending on what's set where. # Anyways, given we need a URL for the API to work properly, we produce a fake # host url by building it out of the relevant cookie properties. fake_url = urllib.parse.urlunsplit(( "http" if is_http_only else "https", # Scheme cookie.domain, # netloc cookie.path, # path '', # query '', # fragment )) params = { 'url' : fake_url, 'name' : cookie.name, 'value' : cookie.value if cookie.value else "", 'domain' : cookie.domain, 'path' : cookie.path, 'secure' : cookie.secure, 'expires' : float(cookie.expires) if cookie.expires else float(2**32), 'httpOnly' : is_http_only, # The "sameSite" flag appears to be a chromium-only extension for controlling # cookie sending in non-first-party contexts. See: # https://bugs.chromium.org/p/chromium/issues/detail?id=459154 # Anyways, we just use the default here, whatever that is. # sameSite = cookie.xxx } ret = self.Network_setCookie(**params) return ret
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L238-L310
create cookie
python
def get_cookie(self, *args): """ Return the (decoded) value of a cookie. """ value = self.COOKIES.get(*args) sec = self.app.config['securecookie.key'] dec = cookie_decode(value, sec) return dec or value
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py#L753-L758
create cookie
python
def write_cookies_to_cache(cj, username): """ Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites. """ mkdir_p(PATH_COOKIES, 0o700) path = get_cookies_cache_path(username) cached_cj = cookielib.MozillaCookieJar() for cookie in cj: cached_cj.set_cookie(cookie) cached_cj.save(path)
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L335-L347
create cookie
python
def _prepare_cookies(self, command, url): """ Extract cookies from the requests session and add them to the command """ req = requests.models.Request() req.method = 'GET' req.url = url cookie_values = requests.cookies.get_cookie_header( self.session.cookies, req) if cookie_values: self._add_cookies(command, cookie_values)
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L89-L102
create cookie
python
def load_cookie(cls, request, key='session', secret_key=None): """Loads a :class:`SecureCookie` from a cookie in request. If the cookie is not set, a new :class:`SecureCookie` instanced is returned. :param request: a request object that has a `cookies` attribute which is a dict of all cookie values. :param key: the name of the cookie. :param secret_key: the secret key used to unquote the cookie. Always provide the value even though it has no default! """ data = request.cookies.get(key) if not data: return cls(secret_key=secret_key) return cls.unserialize(data, secret_key)
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/securecookie.py#L286-L301
create cookie
python
def cookiejar(name='session'): """ Ready the CookieJar, loading a saved session if available @rtype: cookielib.LWPCookieJar """ log = logging.getLogger('ipsv.common.cookiejar') spath = os.path.join(config().get('Paths', 'Data'), '{n}.txt'.format(n=name)) cj = cookielib.LWPCookieJar(spath) log.debug('Attempting to load session file: %s', spath) if os.path.exists(spath): try: cj.load() log.info('Successfully loaded a saved session / cookie file') except cookielib.LoadError as e: log.warn('Session / cookie file exists, but could not be loaded', exc_info=e) return cj
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/__init__.py#L88-L104
create cookie
python
def cookies(self): """A :class:`dict` with the contents of all cookies transmitted with the request.""" return parse_cookie( self.environ, self.charset, self.encoding_errors, cls=self.dict_storage_class, )
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_request.py#L514-L522
create cookie
python
def _load_cookie(self): """Loads HTTP Cookie from environ""" cookie = SimpleCookie(self._environ.get('HTTP_COOKIE')) vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name] # no session was started yet if not vishnu_keys: return morsel = cookie[vishnu_keys[0]] morsel_value = morsel.value if self._config.encrypt_key: cipher = AESCipher(self._config.encrypt_key) morsel_value = cipher.decrypt(morsel_value) received_sid = Session.decode_sid(self._config.secret, morsel_value) if received_sid: self._sid = received_sid else: logging.warn("found cookie with invalid signature")
https://github.com/anomaly/vishnu/blob/5b3a6a69beedc8554cc506ddfab273760d61dc65/vishnu/session.py#L252-L273
create cookie
python
def _cookie_attrs(self, cookies): """Return a list of cookie-attributes to be returned to server. like ['foo="bar"; $Path="/"', ...] The $Version attribute is also added when appropriate (currently only once per request). """ # add cookies in order of most specific (ie. longest) path first cookies.sort(key=lambda a: len(a.path), reverse=True) version_set = False attrs = [] for cookie in cookies: # set version of Cookie header # XXX # What should it be if multiple matching Set-Cookie headers have # different versions themselves? # Answer: there is no answer; was supposed to be settled by # RFC 2965 errata, but that may never appear... version = cookie.version if not version_set: version_set = True if version > 0: attrs.append("$Version=%s" % version) # quote cookie value if necessary # (not for Netscape protocol, which already has any quotes # intact, due to the poorly-specified Netscape Cookie: syntax) if ((cookie.value is not None) and self.non_word_re.search(cookie.value) and version > 0): value = self.quote_re.sub(r"\\\1", cookie.value) else: value = cookie.value # add cookie-attributes to be returned in Cookie header if cookie.value is None: attrs.append(cookie.name) else: attrs.append("%s=%s" % (cookie.name, value)) if version > 0: if cookie.path_specified: attrs.append('$Path="%s"' % cookie.path) if cookie.domain.startswith("."): domain = cookie.domain if (not cookie.domain_initial_dot and domain.startswith(".")): domain = domain[1:] attrs.append('$Domain="%s"' % domain) if cookie.port is not None: p = "$Port" if cookie.port_specified: p = p + ('="%s"' % cookie.port) attrs.append(p) return attrs
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1275-L1332
create cookie
python
def set(self, name, value, domain, **kwargs): """Add new cookie or replace existing cookie with same parameters. :param name: name of cookie :param value: value of cookie :param kwargs: extra attributes of cookie """ if domain == 'localhost': domain = '' self.cookiejar.set_cookie(create_cookie(name, value, domain, **kwargs))
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L176-L187
create cookie
python
def _set_cookies(self, cookies): """设置雪球 cookies,代码来自于 https://github.com/shidenggui/easytrader/issues/269 :param cookies: 雪球 cookies :type cookies: str """ cookie_dict = helpers.parse_cookies_str(cookies) self.s.cookies.update(cookie_dict)
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L56-L63
create cookie
python
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): """ Add a new cookie """ newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if max_age is not None: newcookie['max-age'] = max_age if expires is not None: newcookie['expires'] = expires if path is not None: newcookie['path'] = path if domain is not None: newcookie['domain'] = domain if secure: newcookie['secure'] = secure if httponly: newcookie['httponly'] = httponly self.sent_cookies = [c for c in self.sent_cookies if c.key != key] self.sent_cookies.append(newcookie)
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/http.py#L175-L196
create cookie
python
def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value. """ value = self.cookies.get(key) if secret: # See BaseResponse.set_cookie for details on signed cookies. if value and value.startswith('!') and '?' in value: sig, msg = map(tob, value[1:].split('?', 1)) hash = hmac.new(tob(secret), msg, digestmod=digestmod).digest() if _lscmp(sig, base64.b64encode(hash)): dst = pickle.loads(base64.b64decode(msg)) if dst and dst[0] == key: return dst[1] return default return value or default
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1215-L1231
create cookie
python
def login_with_cookies(self, cookies): """使用cookies文件或字符串登录知乎 :param str cookies: ============== =========================== 参数形式 作用 ============== =========================== 文件名 将文件内容作为cookies字符串 cookies 字符串 直接提供cookies字符串 ============== =========================== :return: 无 :rtype: None """ if os.path.isfile(cookies): with open(cookies) as f: cookies = f.read() cookies_dict = json.loads(cookies) self._session.cookies.update(cookies_dict)
https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/client.py#L82-L99
create cookie
python
def save_cookie(self, response, key='session', expires=None, session_expires=None, max_age=None, path='/', domain=None, secure=None, httponly=False, force=False): """Saves the SecureCookie in a cookie on response object. All parameters that are not described here are forwarded directly to :meth:`~BaseResponse.set_cookie`. :param response: a response object that has a :meth:`~BaseResponse.set_cookie` method. :param key: the name of the cookie. :param session_expires: the expiration date of the secure cookie stored information. If this is not provided the cookie `expires` date is used instead. """ if force or self.should_save: data = self.serialize(session_expires or expires) response.set_cookie(key, data, expires=expires, max_age=max_age, path=path, domain=domain, secure=secure, httponly=httponly)
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/securecookie.py#L303-L321
create cookie
python
def should_set_cookie(self, app: 'Quart', session: SessionMixin) -> bool: """Helper method to return if the Set Cookie header should be present. This triggers if the session is marked as modified or the app is configured to always refresh the cookie. """ if session.modified: return True save_each = app.config['SESSION_REFRESH_EACH_REQUEST'] return save_each and session.permanent
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L161-L170
create cookie
python
def cookies(self): '''Simplified Cookie access''' return { key: self.raw_cookies[key].value for key in self.raw_cookies.keys() }
https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/request.py#L32-L37
create cookie
python
def setCookies(browser, domain, cookieJar): """ Writes all given cookies to the given browser Returns: bool - True if successful, false otherwise """ return BrowserCookies.browsers[browser].writeCookies(domain, cookieJar)
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/http/browser/BrowserCookies.py#L56-L62
create cookie
python
def get_cookie_string(cls, url, user_agent=None, **kwargs): """ Convenience function for building a Cookie HTTP header value. """ tokens, user_agent = cls.get_tokens(url, user_agent=user_agent, **kwargs) return "; ".join("=".join(pair) for pair in tokens.items()), user_agent
https://github.com/Anorov/cloudflare-scrape/blob/f35c463a60d175f0252b1e0c8e14a284e9d4daa5/cfscrape/__init__.py#L205-L210
create cookie
python
def parse_cookie(cookie): """Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. """ cookiedict = {} for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: # Assume an empty name per # https://bugzilla.mozilla.org/show_bug.cgi?id=169091 key, val = str(''), chunk key, val = key.strip(), val.strip() if key or val: # unquote using Python's algorithm. cookiedict[key] = unquote_cookie(val) return cookiedict
https://github.com/squeaky-pl/japronto/blob/a526277a2f59100388c9f39d4ca22bfb4909955b/src/japronto/request/__init__.py#L131-L150
create cookie
python
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) return decode_signed_value( self.application.settings["cookie_secret"], name, value, max_age_days=max_age_days, min_version=min_version, )
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L745-L775
create cookie
python
def login(self, user=None, password=None, **kwargs): """ 雪球登陆, 需要设置 cookies :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :return: """ cookies = kwargs.get('cookies') if cookies is None: raise TypeError('雪球登陆需要设置 cookies, 具体见' 'https://smalltool.github.io/2016/08/02/cookie/') headers = self._generate_headers() self.s.headers.update(headers) self.s.get(self.LOGIN_PAGE) cookie_dict = helpers.parse_cookies_str(cookies) self.s.cookies.update(cookie_dict) log.info('登录成功')
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xq_follower.py#L27-L46
create cookie
python
def set_session(self, cookies): """ sets the cookies (should be a dictionary) """ self.__session.cookies = requests.utils.cookiejar_from_dict(cookies)
https://github.com/haochi/personalcapital/blob/2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f/personalcapital/personalcapital.py#L97-L101
create cookie
python
def COOKIES(self): """ Cookies parsed into a dictionary. Signed cookies are NOT decoded automatically. See :meth:`get_cookie` for details. """ raw_dict = SimpleCookie(self.headers.get('Cookie','')) cookies = {} for cookie in six.itervalues(raw_dict): cookies[cookie.key] = cookie.value return cookies
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L986-L994
create cookie
python
def get_bdstoken(cookie): '''从/disk/home页面获取bdstoken等token信息 这些token对于之后的请求非常重要. ''' url = const.PAN_REFERER req = net.urlopen(url, headers={'Cookie': cookie.header_output()}) if req: return parse_bdstoken(req.data.decode()) else: return None
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/auth.py#L285-L295
create cookie
python
def cookie_set(self, name, value): """ Set the value of a client cookie. This can only be called while headers can be sent. :param str name: The name of the cookie value to set. :param str value: The value of the cookie to set. """ if not self.headers_active: raise RuntimeError('headers have already been ended') cookie = "{0}={1}; Path=/; HttpOnly".format(name, value) self.send_header('Set-Cookie', cookie)
https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1219-L1230
create cookie
python
def Network_setCookie(self, name, value, **kwargs): """ Function path: Network.setCookie Domain: Network Method name: setCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'name' (type: string) -> Cookie name. 'value' (type: string) -> Cookie value. Optional arguments: 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. 'domain' (type: string) -> Cookie domain. 'path' (type: string) -> Cookie path. 'secure' (type: boolean) -> True if cookie is secure. 'httpOnly' (type: boolean) -> True if cookie is http-only. 'sameSite' (type: CookieSameSite) -> Cookie SameSite type. 'expires' (type: TimeSinceEpoch) -> Cookie expiration date, session cookie if not set Returns: 'success' (type: boolean) -> True if successfully set cookie. Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. """ assert isinstance(name, (str,) ), "Argument 'name' must be of type '['str']'. Received type: '%s'" % type( name) assert isinstance(value, (str,) ), "Argument 'value' must be of type '['str']'. Received type: '%s'" % type( value) if 'url' in kwargs: assert isinstance(kwargs['url'], (str,) ), "Optional argument 'url' must be of type '['str']'. Received type: '%s'" % type( kwargs['url']) if 'domain' in kwargs: assert isinstance(kwargs['domain'], (str,) ), "Optional argument 'domain' must be of type '['str']'. Received type: '%s'" % type( kwargs['domain']) if 'path' in kwargs: assert isinstance(kwargs['path'], (str,) ), "Optional argument 'path' must be of type '['str']'. Received type: '%s'" % type( kwargs['path']) if 'secure' in kwargs: assert isinstance(kwargs['secure'], (bool,) ), "Optional argument 'secure' must be of type '['bool']'. Received type: '%s'" % type( kwargs['secure']) if 'httpOnly' in kwargs: assert isinstance(kwargs['httpOnly'], (bool,) ), "Optional argument 'httpOnly' must be of type '['bool']'. Received type: '%s'" % type( kwargs['httpOnly']) expected = ['url', 'domain', 'path', 'secure', 'httpOnly', 'sameSite', 'expires'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['url', 'domain', 'path', 'secure', 'httpOnly', 'sameSite', 'expires']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Network.setCookie', name=name, value=value, **kwargs) return subdom_funcs
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L2271-L2329
create cookie
python
def init(self): """Returns a tuple pair of cookie and crumb used in the request""" url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker) r = requests.get(url) txt = r.content cookie = r.cookies['B'] pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}') for line in txt.splitlines(): m = pattern.match(line.decode("utf-8")) if m is not None: crumb = m.groupdict()['crumb'] crumb = crumb.replace(u'\\u002F', '/') return cookie, crumb
https://github.com/AndrewRPorter/yahoo-historical/blob/7a501af77fec6aa69551edb0485b665ea9bb2727/yahoo_historical/fetch.py#L26-L39
create cookie
python
def new_request_session(config, cookies): """Create a new request session.""" session = requests.Session() if cookies: session.cookies = cookies session.max_redirects = config["maxhttpredirects"] session.headers.update({ "User-Agent": config["useragent"], }) if config["cookiefile"]: for cookie in cookies.from_file(config["cookiefile"]): session.cookies = requests.cookies.merge_cookies(session.cookies, cookie) return session
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/director/aggregator.py#L41-L53
create cookie
python
def generate_edit_credentials(self): """ request an edit token and update the cookie_jar in order to add the session cookie :return: Returns a json with all relevant cookies, aka cookie jar """ params = { 'action': 'query', 'meta': 'tokens', 'format': 'json' } response = self.s.get(self.base_url, params=params) self.edit_token = response.json()['query']['tokens']['csrftoken'] return self.s.cookies
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_login.py#L144-L157
create cookie
python
def cookie_encode(data, key, digestmod=None): """ Encode and sign a pickle-able object. Return a (byte) string """ depr(0, 13, "cookie_encode() will be removed soon.", "Do not use this API directly.") digestmod = digestmod or hashlib.sha256 msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=digestmod).digest()) return tob('!') + sig + tob('?') + msg
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L3042-L3049
create cookie
python
def add_cookie_header(self, request): """Add correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide_cookie2 is true. """ _debug("add_cookie_header") self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) cookies = self._cookies_for_request(request) attrs = self._cookie_attrs(cookies) if attrs: if not request.has_header("Cookie"): request.add_unredirected_header( "Cookie", "; ".join(attrs)) # if necessary, advertise that we know RFC 2965 if (self._policy.rfc2965 and not self._policy.hide_cookie2 and not request.has_header("Cookie2")): for cookie in cookies: if cookie.version != 1: request.add_unredirected_header("Cookie2", '$Version="1"') break finally: self._cookies_lock.release() self.clear_expired_cookies()
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1334-L1365
create cookie
python
def set_cookie(self, cookie=None): """Set the Cookie header.""" if cookie: self._cookie = cookie.encode() else: self._cookie = None
https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/socketio.py#L91-L96
create cookie
python
def client_cookie_jar(self): """ Return internal cookie jar that must be used as HTTP-request cookies see :class:`.WHTTPCookieJar` :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() cookie_header = self.get_headers('Cookie') for cookie_string in (cookie_header if cookie_header is not None else tuple()): for single_cookie in WHTTPCookieJar.import_header_text(cookie_string): cookie_jar.add_cookie(single_cookie) return cookie_jar.ro()
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L230-L243
create cookie
python
def spawn(self, url, force_spawn=False): """use the url for creation of domain and fetch cookies - init cache dir by the url domain as ``<base>/domain`` - save the cookies to file ``<base>/domain/cookie.txt`` - init ``headers.get/post/json`` with response info - init ``site_dir/site_raw/site_media`` :param url: :type url: :param force_spawn: :type force_spawn: :return: :rtype: """ _url, domain = self.get_domain_home_from_url(url) if not _url: return False self.cache['site_dir'] = os.path.join(self.cache['base'], self.domain) for k in ['raw', 'media']: self.cache['site_' + k] = os.path.join(self.cache['site_dir'], k) helper.mkdir_p(self.cache['site_' + k], True) ck_pth = os.path.join(self.cache['site_dir'], 'cookie.txt') helper.mkdir_p(ck_pth) name = os.path.join(self.cache['site_raw'], 'homepage') # not force spawn and file ok if not force_spawn and helper.is_file_ok(name): # zlog.debug('{} exist!'.format(name)) self.sess.cookies = self.load_cookies(ck_pth) return True else: zlog.debug('{} not exist!'.format(name)) res = self.sess.get(url, headers=self.__header__) if res.status_code != 200: return False if res: helper.write_file(res.content, name) # self.load(url) for k, v in self.headers.items(): self.headers[k] = res.request.headers self.dump_cookies(cookies=self.sess.cookies, save_to=ck_pth) return True
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L179-L227
create cookie
python
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L578-L581
create cookie
python
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L508-L526
create cookie
python
def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/examples/analytics/reports.py#L40-L47