web framework and Django

web application

What is web

A web application is an application that can be accessed through the Web. The biggest benefit of the program is that it is easy for users to access the application. Users only need to have a browser and do not need to install other software.

The application has two modes: C/S and B/S. C/S is a client/server program, which means that such programs generally run independently. B/S is a browser-side/server-side application. This type of application is generally run with the help of browsers such as IE. WEB applications are generally in B/S mode. Web applications are first and foremost “applications” and are not fundamentally different from programs written in standard programming languages, such as C, C++, etc. However, Web applications have their own unique features, that is, they are based on the Web rather than running using traditional methods. In other words, it is a product of the typical browser/server architecture.

A web framework is a framework written by others. We only need to fill in the code at a fixed location.

Advantages and disadvantages of web programs

advantage:

  • Web applications do not require any complicated “unfolding” process, all that is required is a suitable browser;
  • Web applications often consume little or no user hard drive space;
  • They do not need to be updated because all new features are implemented on the server and thus automatically communicated to the client;
  • Network applications and server-side network products are easily integrated, such as email functions and search functions;
  • Because they run in a web browser window, most of the time they are used across platforms (e.g. Windows, Mac, Linux, etc.)

shortcoming:

  • Web applications emphasize browser suitability. If the browser does not provide a specific function, or deprecates a specific platform or operating system version (making it inapplicable), it will affect a large number of users;
  • Network applications rely on application files on the remote server side of the Internet. Therefore, when there is a problem with the connection, the app will not work properly.
  • Many network applications are not open source and can only rely on services provided by third parties. Therefore, they cannot be customized and personalized for users, and in most cases users cannot use them offline, so A lot of flexibility is lost;
  • They are completely dependent on the availability of application service providers. If the company goes bankrupt and the server stops being used, users will not be able to recover their previous information. In contrast, even if the software manufacturer goes out of business, traditional installation software can continue to run, although it can no longer be updated or served by other users;
  • Similarly, the provider company has greater control over the software and its functionality. They can add new features to the software if they want, even if users want to wait for bugs to be resolved before updating. Skipping inferior software versions is also no longer possible. Companies can impose undesirable features on users, or they can reduce bandwidth at will to cut costs.
  • The company can theoretically retrieve any user behavior. This may cause privacy security issues.
Advantages of B\S architecture
  • This architecture uses the standard communication protocol on the Internet (usually TCP/IP protocol) as the protocol for client to communicate with the server. This allows anyone located anywhere on the Internet to access the server normally. For the server, data can be processed through corresponding Web services and database services. Standard communication protocols are used externally to share data.
  • Process the data on the server and generate a web page based on the processing results to facilitate direct downloading by the client.
  • The processing of data on the client is further simplified, using the browser as a client application to display the data. There is no longer a need to write and install separate other types of applications for clients. In this way, the client only needs to install an operating system with a built-in browser, and directly install a browser to access data on the server. The browser is a standard device of the computer
    • The browser is the socket client, and the server is the socket server.

Writing web applications based on socket

Before writing, first understand the four major characteristics of http:

Characteristics of HTTP protocol:
1. Four major characteristics
Response based on request
Application layer protocol based on TCP protocol
no status
short link

2. Request data format
Request first line (request method, protocol, version number, path)
Request header
\r\

Request body (the get request method does not have a request body, only the POST request method has a request body)
3. Response data format
Response first line()
response header
\r\

response body()
4. Response status code
1xx
2xx
3xx
4xx
5xx

Request method
GET POST

Usage of wsgiref module

It is a built-in module that can be used directly without installation. It helps us encapsulate sockets and solves some high concurrency problems, but it only solves part of it. It can also help us process data in http format. Encapsulation processing does not require us to handle it.

views.py is mainly used to write business logic. It is also called a view file.
urls.py is mainly used to write the correspondence between suffixes and view functions. It is also called a routing file.
template stores template files, html files, and template text used in the project, and provides some template syntax.

startup file;

from wsgiref.simple_server import make_server
from urlss import urls


def run(env, response):
    response('200 ok', [])# env: When requesting data, all the data carried is here
    print(env) #response: the data the server responds to the client
    current_path = env.get('PATH_INFO')

    func=None
    for url in urls: # url is the tuple inside
        if current_path == url[0]:
            func = url[1]
            break

    if func:
        res = func()
        return [res.encode('utf-8')]
    else:
        return b'404 error'

if __name__ == '__main__':
    server = make_server('127.0.0.1', 8000, app=run)
    """
    It can monitor '127.0.0.1', 8000 in real time. This address will respond as long as the client connects.
    app=run means that when the client has a request, the request will be handed over to the run function for processing, without brackets.
    What is written in Django is the function name. This function will be called when a request is accepted. Function + brackets
    If it is the flask framework, after receiving the request, it will also be handed over to the object for processing, but the object + () becomes the execution of __call__
    
    """
    server.serve_forever() # Start framework

urls file

from vlwes import *
urls = (
    ('/index', index),
    ('/home', home),
)

vlwes file

def index():
    return 'from index'


def home():
    return 'from home'

When we add functions in the future, we can write the functions directly in vlwes, then return the information from the urls file, and start it using the wsgiref file. We can also read the content in the text or the content in the web page.

You can even visit other websites through our own URL

When we use multiple HTML, there will be many files crowded into one folder. We can create a new folder and put them in it.

Django framework

Python’s mainstream framework

Mainstream frameworks in Python:
Django framework: the most mainstream, with a market share of more than 90%. It is a bulky framework with heavy modules. It is not suitable for small projects and is similar to an aircraft carrier.
Falsk framework: lightweight, small and beautiful, with relatively few built-in functions, and requires the installation of many third-party modules. When you install enough modules, it is almost the same as Django.
tornado framework: asynchronous, non-blocking, high performance, the cost of learning this framework is a bit high, and the amount of concurrency it solves is quite high. It is generally used in special scenarios.
sanic framework:
Fastapi framework: It is mainly used to write some interfaces. It does not appear on the page. It is only responsible for writing business logic.

How to use Django

Django download: can be downloaded in pycharm:

Notice:

The version of django must match your Python version. For django3, use version 2.7. That won’t work.
django2—–>python3.6 or above
django1—–>python3.6

The project name must be in English, not Chinese

A pycharm window can only open one Django project

Startup project:

How to start a project

First, cut the path to the same directory as manage.py.

Command line startup
python3 manage.py runserver
python3 manage.py runserver 8000

Create Django using the command line:

django-admin startproject project name
django-admin startproject myfirst

pycharm creates project
File
New project
django

After creation, there will be these files

Application

In layman’s terms, Django is a university, and application is the secondary college in the university. A Django project must have at least one application.

Create application:

python.manage.py startapp application name (English)

After creation, you still need to register

Register in settings.py file

The name of the application follows the naming convention of variables.

register:

Enable Django2 version of the page

Introduction to main documents

mysecond # project name
app01 # Application name

migrations # It is a record of migration data
__init__.py
admin.py # Django’s own backend management system
apps.py # Ignore it for now and write some registration stuff
models.py # The model layer, which deals with the database, will be written here when creating tables in the future.
tests.py # test script
views.py # View file, mainly used to write core business logic

mysecond
__init__.py
settings.py #Django’s global configuration file
urls.py # Routing file, correspondence between write address suffix and view function
wsgi.py # wsgiref server
templates # stores HTML files
db.sqlite3 # Django’s own small database
manage.py # Django startup file, entry file