简体   繁体   English

在Python中使用Cookie来存储搜索

[英]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. 我希望能够使用python来实现cookie,以存储用户搜索的内容,并在用户返回时为其提供最近搜索的字段。 is there a way to implement this using the python Cookie library?? 有没有一种方法可以使用python Cookie库来实现?

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.) 如果您不想输入名称或其他任何内容,可以尝试使用浏览器的IP地址作为会话的密钥(这可能会成为噩梦,但您可以尝试。)

  3. Using the session identification (username or IP address), save the searches in a database on your server. 使用会话标识(用户名或IP地址),将搜索保存在服务器上的数据库中。

  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. 除了会话标识之外,不要相信Cookie有任何其他东西。 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). 当多个人共享相同的IP地址(因为他们共享同一台计算机)时,就会发生意外劫持。

To use cookies you can use whichever API for cookies your framework is using. 要使用cookie,您可以使用框架使用的cookie的API。

Here's a CherryPy full working example for doing what you want, store searches and provide them later. 这是CherryPy完整的工作示例,可用于执行所需操作,存储搜索并在以后提供。

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. 它使用json序列化列表并将其作为字符串存储在cookie中。 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. Python json是在python 2.6中引入的,因此,如果在2.6之前需要它,那么如果没有2.6,则可以使用simplejson来运行示例。

Sorry about the HTML in the code. 抱歉,代码中的HTML。 That would ideally be outside the code, in a template file, using a template engine such as jinja2. 理想情况下,使用诸如jinja2之类的模板引擎将其放在代码之外的模板文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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