1. Use of cookies

    A cookie (sometimes also used in its plural form cookies) refers to the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user and track the session.

    In real applications, the server can use the arbitrariness of the information contained in the cookie to filter and regularly maintain the information to judge the status in the HTTP transmission.

    The most typical application of cookies is to determine whether a registered user has logged in to the website, and the user may be prompted whether to retain the user information when entering the website next time to simplify the login procedure. These are the functions of cookies.

    Another important application is the handling of "shopping carts" and the like.

    Users may select different items on different pages of the same website over a period of time, and this information will be written to cookies so that the information can be extracted at the time of final payment.

    

    Direct manipulation of generic cookies and secure cookies is provided in the Tornado framework.

    A secure cookie means that the cookie stored on the client is encrypted, and the client can only view the encrypted data.

    In the Tornado framework, the syntax for common methods of using normal cookies and secure cookies is as follows:

        1) set_cookie('name', value): set cookie.

        2) get_cookie('name'): Get the cookie.

        3) set_secure_cookie('name', value): Set the secure cookie value.

        4 ) get_secure_cookie ( 'name ' ) : Get the secure cookie value .

        5) clear_cookie('name'): Clear the cookie value named name.

        6) clear_all_cookies(): Clear all cookies.

    Example:

    Set and get cookie values ​​on different pages.

import tornado.ioloop #异步网络功能库import tornado.web #创建Web应用程序的Web框架。import tornado.escape #常用函数和类
#定义子类,设置cookie的值class MainHandler(tornado.web.RequestHandler): def get(self): #URL编码处理 self.set_cookie('odn_cookie',tornado.escape.url_escape("未加密COOKIE串")) #设置普通cookie self.set_secure_cookie('scr_cookie',"加密SCURE_COOKIE串") #设置加密cookie self.write("<a href='/shcook'>查看设置的COOKIE</a>")
#定义处理类shcookHdl,用于获取cookie的值。class shcookHdl(tornado.web.RequestHandler): def get(self): #获取普通cookie odn_cookie = tornado.escape.url_unescape(self.get_cookie('odn_cookie')) #进行URL解码 scr_cookie = self.get_secure_cookie('scr_cookie').decode('utf-8') #获取加密cookie self.write("普通COOKIE:%s,<br/>安全COOKIE:%s"%(odn_cookie,scr_cookie))
#定义应用配置函数app = tornado.web.Application([ (r"/sscook",MainHandler), #使用正则表达式获取参数 (r"/shcook",shcookHdl), ],cookie_secret='aaabbbccc##$$3232sdaf##fsdd')
if __name__ == '__main__': app.listen(8080) #设置监听服务器8080端口 tornado.ioloop.IOLoop.instance().start()

    analyze:

        The first is to import the corresponding module.

        Then define the subclass to set the value of the cookie.

            By overriding the get() function,

                .set_cookie() is to set a cookie;

                tornado.escape.url_escape() : Returns the URL-encoded version of the given value.

                .set_secure_cookie() is to set the secure cookie value.

        Then define a subclass to get the value of the cookie.

            By overriding the get() function,

                .get_cookie ie() : Get the value of the cookie. 'odn_cookie' is to set the cookie value through .set_cookie() .

            .get_secure_cookie() : Get the value of the secure cookie, and the cookie is two parts.

        Then configure the two custom classes above through tornado.web.Application () .

            cookie_secret = 'aaabbbccc##$$3232sdaf##fsdd' : used to sign cookies.

        Finally set the port and start.

    operation result:

picture

    Type in the address bar of the web page: http://localhost:8080/sscool

picture

    Click "View Settings Cookies"

picture

    The reason why you can click to jump here is also because the <a> tag and hyperlink tag of the web page are used.

2. URL redirection

    The so-called URL redirection is to guide users who visit the current domain name to another URL page specified by you through the special settings of the server.

    The function of URL redirection can be realized in the Tornado framework, which needs to be realized by the following two methods.

        1) redirect(url): redirect to URL in business logic.

        2) RedirectHandler: realizes the direct redirection of a URL.

            Syntax format:

(r'/aaa',tornado.Web.RedirectHandler,dict(url='/abc'))

    Example:

    Implement two URL forwarding functions.

import tornado.ioloop #异步网络功能库import tornado.web #创建Web应用程序的Web框架。
#定义子类,作为转向的目标URL请求处理程序class DistA(tornado.web.RequestHandler): def get(self): self.write("被转向的目标页面!")
#定义转向处理器的类class SrcA(tornado.web.RequestHandler): def get(self): self.redirect('/dist')
#定义应用配置函数app = tornado.web.Application([ (r"/dist",DistA), #使用正则表达式获取参数 (r"/src",SrcA), (r"/rdrt",tornado.web.RedirectHandler,{'url':'/src'}), ])
if __name__ == '__main__': app.listen(8080) #设置监听服务器8080端口 tornado.ioloop.IOLoop.instance().start()

    analyze:

        The first is to import the module and define a subclass DistA for outputting pages.

        Then a subclass SrcA is defined, and self.redirect( '/dist' ) is used in get() to jump to the URL http://localhost:8080/dist.

        Through the tornado.web.Application configuration, if you enter "/dist" in the URL, the DistA class will be executed ; if you enter "/src" , the SrcA class will be executed, and the SrcA class uses .redirect( '/dist' ) to jump , so jump to http ://localhost:8080/dist without delay .

        And input "/rdrt" , it uses a direct jump method, jumps to "/src" , and then jumps to http://localhost:8080/ because of the .redirect( '/dist' ) setting dist this URL .

    operation result:

picture

    Enter http://localhost:8080/ dist , http://localhost:8080/src or http://localhost:8080/rdrt in the URL, it will jump to http://localhost:8080/ dist this URL page .

    

picture

    If you enter another URL, you will be prompted:

picture

    Because this URL is not set.

3. Use static resource files

    Most web applications have a set of files that are the same for all users and that do not change while the application is running.

    These can be media files used for URL decoration, such as pictures, CSS style sheets that describe how to draw the web page on the screen, JavaScript code that can be downloaded and executed by the browser, HTML pages without dynamic content, etc.

    These files that do not change are called static resource files.

    Tornado framework supports the direct use of static resource files, such as images, Javascript scripts, CSS styles, etc. in URL pages.

    When you need to use static file resources, you need to provide the "static_path" parameter when initializing the Application class.

    Example:

    Use image static resource files.

import tornado.ioloop #异步网络功能库import tornado.web #创建Web应用程序的Web框架。import osBASE_DIR = os.path.dirname(__file__)#定义子类,作为转向的目标URL请求处理程序class MainHandler(tornado.web.RequestHandler):    def get(self):        self.write("<img src='/static/aa.jpg'/>")        self.write(BASE_DIR)

#定义应用配置函数app = tornado.web.Application([ (r"/stt",MainHandler), #使用正则表达式获取参数 ],static_path='./static')
if __name__ == '__main__': app.listen(8080) #设置监听服务器8080端口 tornado.ioloop.IOLoop.instance().start()

    analyze:

        The first is to import the corresponding module,

        The line BASE_DIR = os.path.dirname(__file__) can display the root directory address of the current project.

        Then it is to define a subclass of display page, and use the <img> tag to display an image in the page. src is an attribute that corresponds to the file path.

        It should be noted here that the static folder in the relative path of the currently specified file seems to be fixed, so you need to receive and create one. The subfolders inside can be customized, that is, img, css, js and other folders.

        Then at the end of the tornado.web.Application section, set static_path= './static' , which is actually declared in the static folder, those fixed data.

        It should also be noted that if you change it to another name, the picture will not be displayed normally, but if you change it back, it will be displayed, which also makes me stuck for a long time.

        (Maybe you want to use this static folder as a fixed storage location?)

        The last is the same port settings and startup.

    operation result:

picture

    Enter the URL http://localhost:8080/stt in the webpage

    

picture