简体   繁体   中英

Using cookies with python to store searches

Hey i have a webpage for searching a database. i would like to be able to implement cookies using python to store what a user searches for and provide them with a recently searched field when they return. is there a way to implement this using the python Cookie library??

Usually, we do the following.

  1. Use a framework.

  2. Establish a session. Ideally, ask for a username of some kind. If you don't want to ask for names or anything, you can try to the browser's IP address as the key for the session (this can turn into a nightmare, but you can try it.)

  3. Using the session identification (username or IP address), save the searches in a database on your server.

  4. When the person logs in again, retrieve their query information from your local database.

Moral of the story. Don't trust the cookie to have anything it but session identification. And even then, it will get hijacked either on purpose or accidentally.

  • Intentional hijacking is the way one person poses as another.

  • Accident hijacking occurs when multiple people share the same IP address (because they share the same computer).

To use cookies you can use whichever API for cookies your framework is using.

Here's a CherryPy full working example for doing what you want, store searches and provide them later.

import cherrypy
import json

class Root(object):
    def index(self):
        last_search = cherrypy.request.cookie.get('terms', None)
        if last_search: 
            last_search = ','.join(json.loads(last_search.value))
        else:
            last_search = 'None'
        return """
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Search</title>
</head>
<body>
    <h1>Search</h1>
    <form action="do_search" method="get">
        <p>Please type your search terms: 
        <input type="text" name="query" /></p>
        <p>Hint: Last 5 used terms: %s</p>
        <p><input type="submit" value="Search &rarr;" /></p>
    </form>
</body>
""" % (last_search,)
    index.exposed = True

    def do_search(self, query):
        results = ['some', 'results', 'here', 'simulating', 'a', 'search']
        print cherrypy.request.cookie
        last_search = cherrypy.request.cookie.get('terms', None)
        if last_search:
            last_search = json.loads(last_search.value)[-4:] # get last 4
        else:
            last_search = []
        last_search.append(query) # append new term
        cherrypy.response.cookie['terms'] = json.dumps(last_search)
        return """
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Search</title>
</head>
<body>
    <h1>Search Results for %r</h1>
    <p>%s</p>
    <p><a href="%s">click here to search again</a>
    </p>
</body>
""" % (query, ', '.join(results), cherrypy.url('/'))
    do_search.exposed = True

application = cherrypy.tree.mount(Root(), '/')

if __name__ == '__main__':
    cherrypy.quickstart()

NOTES:

It uses json to serialize the list and store it in the cookie as a string. Python json was introduced in python 2.6, so if you need it before 2.6, so if you don't have 2.6 you can use simplejson instead to run the example.

Sorry about the HTML in the code. That would ideally be outside the code, in a template file, using a template engine such as jinja2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM