Python set cookies

25 Python code examples are found related to " set cookies". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: cookies.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def setCookiesFromUrl(self, cookies, url):
        """Add the cookies in the cookies list to this cookie jar.

        Args:
            cookies: A list of QNetworkCookies.
            url: The URL to set the cookies for.

        Return:
            True if one or more cookies are set for 'url', otherwise False.
        """
        accept = config.instance.get('content.cookies.accept', url=url)

        if 'log-cookies' in objects.debug_flags:
            log.network.debug('Cookie on {} -> applying setting {}'
                              .format(url.toDisplayString(), accept))

        if accept == 'never':
            return False
        else:
            self.changed.emit()
            return super().setCookiesFromUrl(cookies, url) 
Example 2
Source File: config.py    From DataSpider with GNU General Public License v3.0 6 votes vote down vote up
def set_cookies(firefox_cookies_path: Optional[str]):
    """
    显式设置Cookies
    :param firefox_cookies_path:
    :return:
    """
    global __COOKIES_PATH
    __COOKIES_PATH = firefox_cookies_path
    if firefox_cookies_path is None:
        warn("Haven't set a valid cookies path, use default.")
        get_request_session().cookies = CookieJar()
    else:
        try:
            get_request_session().cookies = _init_cookies(CookieJar(), firefox_cookies_path)
        except:
            warn("Error while loading firefox cookies from: {}, please check it.".format(__COOKIES_PATH))


# If we have default cookies path, set here 
Example 3
Source File: req_urllib.py    From kawaii-player with GNU General Public License v3.0 6 votes vote down vote up
def set_session_cookies(self, cj):
        if cj:
            cj_arr = []
            for i in cj:
                cj_arr.append('{}={}'.format(i.name, i.value))
            self.session_cookies = ';'.join(cj_arr)
        else:
            for i in self.info.walk():
                cookie_list = i.get_all('set-cookie')
                cookie_jar = []
                if cookie_list:
                    for i in cookie_list:
                        cookie = i.split(';')[0]
                        cookie_jar.append(cookie)
                    if cookie_jar:
                        cookies = ';'.join(cookie_jar)
                        self.session_cookies = cookies 
Example 4
Source File: net.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def set_cookies(self, cookie_file):
        '''
        Set the cookie file and try to load cookies from it if it exists.

        Args:
            cookie_file (str): Full path to a file to be used to load and save
            cookies to.
        '''
        try:
            self._cj.load(cookie_file, ignore_discard=True)
            self._update_opener()
            return True
        except:
            return False 
Example 5
Source File: threadlocal.py    From zmirror with MIT License 5 votes vote down vote up
def set_cookies(self, name, value, ttl=12 * 35 * 24 * 60 * 60, path='/'):
        """
        :param ttl: cookie有效时间, 秒
        :type ttl: int
        :type path: str
        :type name:  str
        :type value:  str
        """
        from http.cookies import SimpleCookie
        c = SimpleCookie()
        c[name] = value
        c[name]["path"] = path
        c[name]["expires"] = ttl

        self.extra_cookies[name] = c[name].OutputString() 
Example 6
Source File: SeleniumDrivers.py    From AutoTriageBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setCookies(self, url: str, cookies: Mapping[str, str]) -> None:
        """ Set cookies for the given URL """
        if cookies:
            parsed = urlparse(url)
            # In order to set cookies, we have to go to an html page on the same domain
            self.driver.get(parsed.scheme + '://' + parsed.netloc)
            for key, val in cookies.items():
                self.driver.add_cookie({'name': key, 'value': val, 'domain': parsed.netloc}) 
Example 7
Source File: session_manager.py    From instagram-scraper with MIT License 5 votes vote down vote up
def set_saved_cookies(self, cookie_string):
        if not os.path.exists(self.session_folder):
            os.makedirs(self.session_folder)

        with open(self.session_folder + self.filename,"w+") as f:
            f.write(cookie_string) 
Example 8
Source File: evilginx.py    From evilginx with MIT License 5 votes vote down vote up
def get_set_cookies(data):
    """returns set-cookies headers as a dict"""
    ret = {}
    cargs = data.split('||')
    for ck in cargs:
        ie = ck.find('=')
        sn = ck.find(';')
        if ie > -1 and sn > -1:
            name = ck[:ie]
            val = ck[ie+1:sn]
            ret[name] = unesc_data(val)
    return ret 
Example 9
Source File: spider.py    From zap-api-python with Apache License 2.0 5 votes vote down vote up
def set_option_accept_cookies(self, boolean, apikey=''):
        """
        Sets whether or not a spider process should accept cookies while spidering.
        """
        return six.next(six.itervalues(self.zap._request(self.zap.base + 'spider/action/setOptionAcceptCookies/', {'Boolean': boolean, 'apikey': apikey}))) 
Example 10
Source File: net.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def set_cookies(self, cookie_file):
        """
        Set the cookie file and try to load cookies from it if it exists.
        
        Args:
            cookie_file (str): Full path to a file to be used to load and save
            cookies to.
        """
        try:
            self._cj.load(cookie_file, ignore_discard=True)
            self._update_opener()
            return True
        except:
            return False 
Example 11
Source File: flask_app.py    From BlackSheep with MIT License 5 votes vote down vote up
def set_cookies():
    name = request.args.get('name', 'Hello')
    value = request.args.get('value', 'World')
    response = Response('Hello World', 200, mimetype='text/plain')
    response.set_cookie(name, value)
    return response 
Example 12
Source File: net.py    From script.module.resolveurl with GNU General Public License v2.0 5 votes vote down vote up
def set_cookies(self, cookie_file):
        """
        Set the cookie file and try to load cookies from it if it exists.

        Args:
            cookie_file (str): Full path to a file to be used to load and save
            cookies to.
        """
        try:
            self._cj.load(cookie_file, ignore_discard=True)
            self._update_opener()
            return True
        except:
            return False 
Example 13
Source File: proxy.py    From guppy-proxy with MIT License 5 votes vote down vote up
def set_cookies(self, c):
        if isinstance(c, hcookies.BaseCookie):
            # it's a basecookie
            cookie_pairs = []
            for k in c:
                cookie_pairs.append('{}={}'.format(k, c[k].value))
            header_str = '; '.join(cookie_pairs)
        elif isinstance(c, HTTPRequest):
            # it's a request we should copy cookies from
            try:
                header_str = c.headers.get("Cookie")
            except KeyError:
                header_str = ""
        else:
            # it's a dictionary
            cookie_pairs = []
            for k, v in c.items():
                cookie_pairs.append('{}={}'.format(k, v))
            header_str = '; '.join(cookie_pairs)

        if header_str == '':
            try:
                self.headers.delete("Cookie")
            except KeyError:
                pass
        else:
            self.headers.set("Cookie", header_str) 
Example 14
Source File: third_party_login_core.py    From cape-webservices with Apache License 2.0 5 votes vote down vote up
def set_callback_cookies(resp, success_cb, error_cb):
    resp.cookies['successCallback'] = success_cb
    resp.cookies['successCallback']['expires'] = _COOKIE_EXPIRES
    resp.cookies['successCallback']['httponly'] = True
    resp.cookies['errorCallback'] = error_cb
    resp.cookies['errorCallback']['expires'] = _COOKIE_EXPIRES
    resp.cookies['errorCallback']['httponly'] = True 
Example 15
Source File: network.py    From chromewhip with MIT License 5 votes vote down vote up
def setCookies(cls,
                   cookies: Union['[CookieParam]'],
                   ):
        """Sets given cookies.
        :param cookies: Cookies to be set.
        :type cookies: [CookieParam]
        """
        return (
            cls.build_send_payload("setCookies", {
                "cookies": cookies,
            }),
            None
        ) 
Example 16
Source File: login.py    From steampy with MIT License 5 votes vote down vote up
def set_sessionid_cookies(self):
        sessionid = self.session.cookies.get_dict()['sessionid']
        community_domain = SteamUrl.COMMUNITY_URL[8:]
        store_domain = SteamUrl.STORE_URL[8:]
        community_cookie = self._create_session_id_cookie(sessionid, community_domain)
        store_cookie = self._create_session_id_cookie(sessionid, store_domain)
        self.session.cookies.set(**community_cookie)
        self.session.cookies.set(**store_cookie) 
Example 17
Source File: auth_resources.py    From DIVE-backend with GNU General Public License v3.0 5 votes vote down vote up
def set_cookies(response, cookie_dict, expires=None, domain=current_app.config['COOKIE_DOMAIN']):
    for (k, v) in cookie_dict.iteritems():
        response.set_cookie(k, str(v), expires=expires, domain=domain, secure=True)
    return response


# Expired token
# http://localhost:3009/auth/activate/Imt6aEB0ZXN0LmNvbXUi.C5C0EQ.b55oev3lDumYZby8L5ChLINoD80 
Example 18
Source File: spider.py    From CrawlerMonitor with MIT License 5 votes vote down vote up
def set_cookies(headers, cookieJar):
    if 'Set-Cookies' in headers.keys():
        for cookie in headers['Set-Cookies'].split(';'):
            key, value = cookie.split('=')[0], cookie.split('=')[1]
            cookieJar.set(key, value)
    return { key:value for key,value in cookieJar.items() }

# request homepage and get cookies 
Example 19
Source File: utils.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def set_refresh_cookies(response, encoded_refresh_token, max_age=None):
    """
    Takes a flask response object, and an encoded refresh token, and configures
    the response to set in the refresh token in a cookie. If `JWT_CSRF_IN_COOKIES`
    is `True` (see :ref:`Configuration Options`), this will also set the CSRF
    double submit values in a separate cookie.

    :param response: The Flask response object to set the refresh cookies in.
    :param encoded_refresh_token: The encoded refresh token to set in the cookies.
    :param max_age: The max age of the cookie. If this is None, it will use the
                    `JWT_SESSION_COOKIE` option (see :ref:`Configuration Options`).
                    Otherwise, it will use this as the cookies `max-age` and the
                    JWT_SESSION_COOKIE option will be ignored.  Values should be
                    the number of seconds (as an integer).
    """
    if not config.jwt_in_cookies:
        raise RuntimeWarning("set_refresh_cookies() called without "
                             "'JWT_TOKEN_LOCATION' configured to use cookies")

    # Set the refresh JWT in the cookie
    response.set_cookie(config.refresh_cookie_name,
                        value=encoded_refresh_token,
                        max_age=max_age or config.cookie_max_age,
                        secure=config.cookie_secure,
                        httponly=True,
                        domain=config.cookie_domain,
                        path=config.refresh_cookie_path,
                        samesite=config.cookie_samesite)

    # If enabled, set the csrf double submit refresh cookie
    if config.csrf_protect and config.csrf_in_cookies:
        response.set_cookie(config.refresh_csrf_cookie_name,
                            value=get_csrf_token(encoded_refresh_token),
                            max_age=max_age or config.cookie_max_age,
                            secure=config.cookie_secure,
                            httponly=False,
                            domain=config.cookie_domain,
                            path=config.refresh_csrf_cookie_path,
                            samesite=config.cookie_samesite) 
Example 20
Source File: utils.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def set_access_cookies(response, encoded_access_token, max_age=None):
    """
    Takes a flask response object, and an encoded access token, and configures
    the response to set in the access token in a cookie. If `JWT_CSRF_IN_COOKIES`
    is `True` (see :ref:`Configuration Options`), this will also set the CSRF
    double submit values in a separate cookie.

    :param response: The Flask response object to set the access cookies in.
    :param encoded_access_token: The encoded access token to set in the cookies.
    :param max_age: The max age of the cookie. If this is None, it will use the
                    `JWT_SESSION_COOKIE` option (see :ref:`Configuration Options`).
                    Otherwise, it will use this as the cookies `max-age` and the
                    JWT_SESSION_COOKIE option will be ignored.  Values should be
                    the number of seconds (as an integer).
    """
    if not config.jwt_in_cookies:
        raise RuntimeWarning("set_access_cookies() called without "
                             "'JWT_TOKEN_LOCATION' configured to use cookies")

    # Set the access JWT in the cookie
    response.set_cookie(config.access_cookie_name,
                        value=encoded_access_token,
                        max_age=max_age or config.cookie_max_age,
                        secure=config.cookie_secure,
                        httponly=True,
                        domain=config.cookie_domain,
                        path=config.access_cookie_path,
                        samesite=config.cookie_samesite)

    # If enabled, set the csrf double submit access cookie
    if config.csrf_protect and config.csrf_in_cookies:
        response.set_cookie(config.access_csrf_cookie_name,
                            value=get_csrf_token(encoded_access_token),
                            max_age=max_age or config.cookie_max_age,
                            secure=config.cookie_secure,
                            httponly=False,
                            domain=config.cookie_domain,
                            path=config.access_csrf_cookie_path,
                            samesite=config.cookie_samesite) 
Example 21
Source File: utils.py    From rucio with Apache License 2.0 5 votes vote down vote up
def set_cookies(cookie_dict):
    """
    Sets multiple cookies at once.
    :param cookie_dict: dictionary {'coookie_1_name': value, ... }
    :returns: None
    """
    for cookie_key in cookie_dict:
        if cookie_dict[cookie_key]:
            setcookie(cookie_key, value=cookie_dict[cookie_key], path='/')
    return None 
Example 22
Source File: request.py    From pytest-requests with Apache License 2.0 5 votes vote down vote up
def set_cookies(self, cookies: dict) -> "HttpRequest":
        """ update request cookies
        """
        self.__kwargs["cookies"].update(cookies)
        return self 
Example 23
Source File: httptools.py    From addon with GNU General Public License v3.0 4 votes vote down vote up
def set_cookies(dict_cookie, clear=True, alfa_s=False):
    """
    Guarda una cookie especifica en cookies.dat
    @param dict_cookie: diccionario de  donde se obtienen los parametros de la cookie
        El dict debe contener:
        name: nombre de la cookie
        value: su valor/contenido
        domain: dominio al que apunta la cookie
        opcional:
        expires: tiempo de vida en segundos, si no se usa agregara 1 dia (86400s)
    @type dict_cookie: dict

    @param clear: True = borra las cookies del dominio, antes de agregar la nueva (necesario para cloudproxy, cp)
                  False = desactivado por defecto, solo actualiza la cookie
    @type clear: bool
    """
    
    #Se le dara a la cookie un dia de vida por defecto
    expires_plus = dict_cookie.get('expires', 86400)
    ts = int(time.time())
    expires = ts + expires_plus

    name = dict_cookie.get('name', '')
    value = dict_cookie.get('value', '')
    domain = dict_cookie.get('domain', '')

    #Borramos las cookies ya existentes en dicho dominio (cp)
    if clear:
        try:
            cj.clear(domain)
        except:
            pass

    ck = cookielib.Cookie(version=0, name=name, value=value, port=None, 
                    port_specified=False, domain=domain, 
                    domain_specified=False, domain_initial_dot=False,
                    path='/', path_specified=True, secure=False, 
                    expires=expires, discard=True, comment=None, comment_url=None, 
                    rest={'HttpOnly': None}, rfc2109=False)
    
    cj.set_cookie(ck)
    save_cookies()