Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "what are the knowledge points in Python", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what are the knowledge points in Python" this article.

The development process of WEB

In the earliest days, WEB were static files. The developer directly edits the static HTML page through the editor, and if you want to modify the content or layout of the WEB page, you have to edit these static HTML files. Is it really unpleasant to play like this in the early days?

Because static WEB pages cannot interact with users (submit forms, etc.). To solve this problem, people have developed a technology called CGI (Common Gateway Interface), which is written in C _ Common Gateway Interface +.

Because WEB applications are frequently updated, low-level languages are very unsuitable for efficient development. Because of its high development efficiency and close integration with HTML, scripting languages (JSP, PHP) have quickly replaced the CGI pattern. JSP uses Java to write scripts, while PHP is an open source scripting language.

The earliest dynamic pages were implemented by CGI. How does CGI work? When an address is requested, the http server starts an external program and returns the output of the external program to the user. CGI regulates the way http communicates with external programs.

Entering: through environment variabl

Output: through standard output

Disadvantages of CGI:

The concurrent mode is multi-process

The process is managed by the http server

Based on the above shortcomings of CGI, the FastCGI technology is derived, and the process management is handed over to other services to deal with. The http server converts the http protocol into the fastcgi protocol and sends it to the FastCGI daemon through socket. In this way, there are a variety of concurrency models, and process management is implemented by FastCGI, with a single principle.

Another branch is wsgi technology developed by cgi. Let's take a look at wsgi.

The main key points of the Web framework:

Routin

Request parsing

Response encapsulation

WSGI

The Web Server Gateway Interface (WSGI) is the specification of the standard interface between the Python Web application framework and the Web server.

In the early days of Python Web applications, it was not easy to connect the Web application framework to the Web server because there was no uniform standard. Python Web applications are used for work, specifically by using one of the existing CGI, FastCGI, or mod_python (Apache) standards. This means that applications that work on one Web server may not work on another Web server. In other words, the interoperability between the unified application and the Web server is gone.

WSGI solves this problem by specifying a simple but unified interface between the server and the Web application framework, thus allowing the migration of Web applications.

WSGI specifies two aspects: the server (or gateway) side, and the application or framework side. The WSGI request was processed as follows:

The server executes the application, providing the application with an environment and a callback function.

The application processes the request and returns the response to the server using the callback function provided.

The process is as follows:

Wsgi consists of two parts: container and application. Containers can also be called gateways or servers. The container implements the protocol conversion from http protocol to wsgi protocol; the application is used to deal with business logic.

How do containers communicate with applications? FastCGI communicates through socket;wsgi containers and applications through function calls. Under what circumstances can communication be achieved through function calls? Function calls can be implemented in the same process, and the container and application of wsgi are running in the same process.

Commonly used wsgi container: gunicorn,uWSGI.

A working HelloWorld

With all that said, let's look at a simple example of how wsgi works. Next, implement a helloworld program.

Wsgi application should be a callable object. Functions are callable, and if a class has a _ _ call__ method, it is callable.

The writing of wsgi function has certain requirements. Its function signature is generally as follows, which is relatively fixed:

Def application (environ, start_response): the parameters passed in the''# function are specified: the # environ:environ variable is a dictionary of environment variables passed from the server to the application, such as the request content, and # is defined by the Common Gateway Interface (CGI) specification. WSGI specifies some environment variable trustee # start_response in its specification: a callable object that provides a callback from the server side to the application side, thus enabling # response processing on the server side. It must have two positional parameters. The first should be a status string with an integer state, and the second is a (header_name, header_value) list, which is a tuple that describes the response of the HTTP header. '' pass

The parameters passed in the above function are specified:

Environ:environ variables are dictionaries of environment variables, such as request content, that are passed from the server to the application; they are defined by the Common Gateway Interface (CGI) specification. WSGI specifies some trustees of environmental variables in its specification.

Start_response: a callable object that provides a callback from the server side to the application side, enabling server-side response processing. It must have two positional parameters. The first should be a status string with an integer state, and the second is a (header_name, header_value) list, which is a tuple that describes the response of the HTTP header.

To learn more about WSGI specifications, take a look at the PEP 3333 proposal.

Start writing:

Def application (environ, start_response): body = 'hello world' status =' 200 OK' headers = [('content-type',' text/plain'), ('content-length', str (len (body))] start_response (status, headers) return [body.encode ()] # the above code has only applications and no containers If _ _ name__ = ='_ _ main__': # introduces the wsgi container from wsgiref.simple_server import make_server server = make_server ('0.0.0.0, 8000, application) try: server.serve_forever () except KeyboardInterrupt: server.shutdown ()

Run the above code and access it on the browser:

[lavenliu@VM_113_230_centos 12-web] $python wsgi01.py 183.192.25.121-- [13/Oct/2018 18:48:08] "GET / HTTP/1.1" 200 11183.192.25.121-- [13/Oct/2018 18:48:09] "GET / favicon.ico HTTP/1.1" 200 11183.192.25.121-- [13/Oct/2018 18:48:09] "GET / favicon.ico HTTP/1.1" 200 11

It can also be accessed through the curl command line tool:

Curl-XPOST http://127.0.0.1:8000-d'{"a": 1}'

Next, use the gunicorn container to run the above code:

# first install gunicornpip install gunicorn# and then run the application application of wsgi01.py [lavenliu@VM_113_230_centos 12-web] $gunicorn-b 0.0.0.0 wsgi01:application [2018-10-13 18:55:38 + 0800] [18359] [INFO] Starting gunicorn 19.6.0 [2018-10-13 18:55:38 + 0800] [18359] [INFO] Listening at: http://0.0.0.0:8000 (18359) [2018 -10-13 18:55:38 + 0800] [18359] [INFO] Using worker: sync [2018-10-13 18:55:38 + 0800] [18397] [INFO] Booting worker with pid: 18397

Usually when developing, you can just use wsgiref, and if you are in production, you can use a third-party wsgi container.

In the above code, if you want to see what is in environ, you can add the following code to the above code:

For k, v in environ.items (): print ('{} = > {} '.format (k, v)) # the complete code is as follows: # coding: utf-8def application (environ, start_response): for k, v in environ.items (): print (' {} = > {} '.format (k, v)) body =' hello world' status = '200 OK' headers = [(' content-type', 'text/plain') ('content-length', str (len (body))] start_response (status, headers) return [body.encode ()] # above only the application code There is no container if _ _ name__ ='_ _ main__': from wsgiref.simple_server import make_server server = make_server ('0.0.0.0, 8000, application) try: server.serve_forever () except KeyboardInterrupt: server.shutdown ()

If you run the code again, you will have the following output:

Wsgi.input = > HTTP_ACCEPT_ENCODING = > gzip, deflateHTTP_ACCEPT_LANGUAGE = > zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3SERVER_PORT = > 8000RAW_URI = > / REMOTE_PORT = > 16252HTTP_USER_AGENT = > Mozilla/5.0 (Windows NT 6.3; WOW64 Rv:47.0) Gecko/20100101 Firefox/47.0wsgi.file_wrapper = > REMOTE_ADDR = > 183.192.25.121wsgi.version = > (1,0) wsgi.url_scheme = > httpHTTP_HOST = > 115.159.125.96:8000wsgi.multithread = > FalseHTTP_ACCEPT = > text/html,application/xhtml+xml,application/xml;q=0.9,*/* Q=0.8wsgi.multiprocess = > FalseQUERY_STRING = > SERVER_SOFTWARE = > gunicorn/19.6.0SERVER_PROTOCOL = > HTTP/1.1PATH_INFO = > / HTTP_CONNECTION = > keep-aliveREQUEST_METHOD = > GETwsgi.run_once = > Falsewsgi.errors = > SERVER_NAME = > 0.0.0.0HTTP_CACHE_CONTROL = > max-age=0SCRIPT_NAME = > gunicorn.socket = >

There is a key for QUERY_STRING in environ, and we can print this information:

[lavenliu@VM_113_230_centos 12-web] $cat wsgi01.py # coding: utf-8def application (environ, start_response): print (environ.get ('QUERY_STRING')) body =' hello world' status = '200 OK' headers = [(' content-type', 'text/plain'), (' content-length', str (len (body)] start_response (status) Headers) return [body.encode ()] # above only the application code There is no container if _ _ name__ ='_ _ main__': from wsgiref.simple_server import make_server server = make_server ('0.0.0.0, 8000, application) try: server.serve_forever () except KeyboardInterrupt: server.shutdown ()

In the browser's URL address bar, enter:

Http://115.159.125.96:8000?name=lavenliu&age=25

The running effect is as follows:

[lavenliu@VM_113_230_centos 12-web] $gunicorn-b 0.0.0.0 wsgi01:application [2018-10-13 19:15:36 + 0800] [20609] [INFO] Starting gunicorn 19.6.0 [2018-10-13 19:15:36 + 0800] [20609] [INFO] Listening at: http://0.0.0.0:8000 (20609) [2018-10-13 19:15:36 + 0800] [20609] [INFO] Using worker: Input from the client obtained by sync [2018-10-13 19:15:36 + 0800] [20647] [INFO] Booting worker with pid: 20647name=lavenliu&age=25

In the output above

Input from the client obtained by name=lavenliu&age=25 #

The next step is to parse the input from the client, which is not very difficult, but there is a standard library to handle this parsing, introducing a standard library:

The value returned by from urllib.parse import parse_qsfrom html import escapeparse_qs ('name=lavenliu&age=25') # is a list, because it is possible that key has a

The implementation results are as follows:

{'age': [' 25'], 'name': [' lavenliu']}

The next code is as follows:

[lavenliu@VM_113_230_centos 12-web] $cat wsgi02.py # coding: utf-8from urllib.parse import parse_qsfrom html import escapedef application (environ, start_response): params = parse_qs (environ.get ('QUERY_STRING')) name = params.get (' name', ['anon']) [0] body =' hello {} '.format (name) # if the user enters something illegal in the browser There may be problems status = '200 OK' headers = [(' content-type', 'text/html'), (' content-length', str (len (body))] start_response (status, headers) return [body.encode ()] # above only the application code There is no container if _ _ name__ ='_ _ main__': from wsgiref.simple_server import make_server server = make_server ('0.0.0.0, 8001, application) try: server.serve_forever () except KeyboardInterrupt: server.shutdown ()

If the user enters this in the browser, there may be a problem:

Http://115.159.125.96:8001?name=alert('f**k it') # chrome browser has no problem, it will detect a problem with this input; the above code may be executed if it is on IE6. Navigated to http://115.159.125.96:8001/?%3Cscript%20type=%27text/javascript%27%3Ealert(%27f**k%20it%27)%3C/script%3E?name=alert('f**k it'): 1 The XSS Auditor refused to execute a script in 'http://115.159.125.96:8001/?name=%3Cscript%20type=%27text/javascript%27%3Ealert(%27f**k%20it%27)%3C/script%3E' because its source code was found within the request. The auditor was enabled as the server sent neither an 'XSSMuProtection` nor 'Content-Security-Policy' header.Navigated to http://115.159.125.96:8001/?name=%3Cscript%20type=%27text/javascript%27%3Ealert(%27f**k%20it%27)%3C/script%3E# can be passed in Firefox, and no error will be reported in the # IE11 version, then there is no such problem. These are all the contents of the article "what are the knowledge points in Python?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report