What is a Web framework?
A framework is a restrictive support structure designed to solve an open problem. Using a framework can help you develop a specific system quickly. In short, you can perform on a stage that someone else has built.
We can think of it this way: all Web applications are essentially a socket server, and the user’s browser is a socket client. So we can implement the Web framework ourselves.
Import socket sock = socket.socket(socket.af_inet, socket.sock_stream) sock.bind(('127.0.0.1', 8000))
sock.listen()
while True:
conn, addr = sock.accept()
data = conn.recv(8096)
Add a response status line to the reply message
conn.send(b"HTTP / 1.1 200 OK \ r \ n \ r \ n")
conn.send(b"OK")
conn.close()
Copy the code
The simplest Web application is to save the HTML file, use an off-the-shelf HTTP server software, receive the user’s request, read the HTML from the file, and return it.
Server programs and applications
For a python Web program in real development, there are typically two parts: the server program and the application.
The server program is responsible for the socket server encapsulation, and when the request arrives, the request for various data collation.
The application is responsible for the specific logical processing. In order to facilitate application development, there are many Web frameworks, such as Django, Flask, web.py, etc. Different frameworks develop in different ways, but in any case, the application must work with the server application to serve the user.
Thus, the server program needs to provide different support for different frameworks. This mess is bad for both the server and the framework. The server needs to support a variety of frameworks, and for frameworks, only servers that support it can be used by developed applications.
This is where standardization becomes particularly important. We can set a standard, and as long as the server application supports it and the framework supports it, they can work with it. Once the standard is determined, both sides implement it separately. In this way, the server can support more standards-compliant frameworks, and the framework can use more standards-compliant servers.
WSGI (Web Server Gateway Interface) is a specification that defines the Interface format between Web applications written in Python and Web Server programs to decouple Web applications from Web Server programs.
Common WSGI servers are UWSGi and Gunicorn. The Python standard library provides a standalone WSGI server called WSGIref, which the Django development environment uses as its server.
The server application uses WSGIREF in a normal development environment and uWSGI in a formal hypothetical service coming online.
wsgiref
Replace the Socket Server part of the Web framework we wrote ourselves with wsGIREF module
from wsgiref.simple_server import make_server
from urls import urls
from views import *
def run(env,response):
print(env) # is a dictionary type
# fixed
response('200 OK'[]),The list contains the first line of the request, you can not put it, but must write
Get the current user access path
current_path = env.get('PATH_INFO')
Define a function flag bit
func = None
for url_list in urls: # urls:[[],[],[]] url_list:['',func]
if current_path == url_list[0]:
func = url_list[1]
# End for loop
break
if func:
res = func(env)
else:
# failed to match up error
res = error(env)
return [res.encode('utf-8')]
if __name__ == '__main__':
server = make_server('127.0.0.1',8888,run)
server.serve_forever()
Copy the code
jinja2
In order to query the data from the database, replace the corresponding content in THE HTML and then send it to the browser for rendering, this process is equivalent to the HTML template rendering data, in essence, the HTML content uses some special symbols to replace the data to be displayed. So you can use Jinja2 (template rendering tool)
The principle of template is string replacement. As long as we write in the HTML page following the syntax rules of Jinja2, it will be replaced in accordance with the specified syntax, so as to achieve dynamic return of content.
Django
Application of APP
App is a branch, the project is like a school, app app is like a college, so a project can have multiple app applications
Catalog Introduction:
Py Database model table (ORM) views.py View function (which performs related functions) under the project name __init__.py settings.py Project configuration file urls.py Wsgi. py wsgiref manage.py Project entry file templates houses the HTML fileCopy the code
Create a way
Command line to create a Django project
django-admin startproject mysite
Command line to create app
Python manage.py startApp Application name
Start Django from the command line
python manage.py runserver
Note: There is no templates folder by default when creating from the command line, you need to create it manually and specify the path in the Settings configuration file
Some of the conventions in Django
- The HTML folder is conventionally placed in the Templates folder
The following configuration is required in the setting file, otherwise it needs to be configured
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates'.'DIRS': [os.path.join(BASE_DIR, 'templates')].'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug'.'django.template.context_processors.request'.'django.contrib.auth.context_processors.auth'.'django.contrib.messages.context_processors.messages',],},},]Copy the code
- Static files are stored in the static folder. In general, it is recommended that static folder be divided into CSS, JS and other related folders for hierarchical implementation
Need to be configured in the setting file
Django static file configuration
STATIC_URL = '/static/'
Static file path configuration
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
os.path.join(BASE_DIR,'static1'),
os.path.join(BASE_DIR,'static2'),]Copy the code
Django comes with three basic components
from django.shortcuts import HttpResponse, render, redirect
HttpResponse
An internal string argument is passed back to the browser.
render
In addition to the request argument, it accepts a template file to render and a dictionary argument to hold specific data.
Populate the template file with data and return the results to the browser. (Similar to jinja2 used above)
redirect
Redirect: Takes a URL parameter to redirect to the specified URL.
The difference between Redirect and Render is that redirect takes the path, whereas Render returns the template
Error starting Django
- Django startup error UnicodeEncodeError…
This error is usually reported because the computer name is Chinese, change the English computer name to restart the computer can be.
- SyntaxError: Generator expression must be parenthesized…
This error is usually caused by a compatibility issue between the interpreter and Django. It is recommended to use the 3.6 interpreter to avoid this problem.