Getting Started with Python Web Applications

Introduction

This article is Zenn's online book

"Introduction to self-made Python web applications for third-year web engineers who are sluggish"

This is a partial excerpt from.

Here https://qiita.com/bigen1925/items/dde5575da6c45a91808d Please also read.

Try writing a web server in Python

Suddenly, let's create a server that receives a request from a browser in Python and returns a response to the browser. The following program starts as a server on port 8080 (localhost: 8080) of your PC, writes the contents to a file called server_recv.txt when receiving a request from the browser, and then server_send.txt Reads the contents of the file and returns it to the browser as a response.

TCPServer.py

import socket


class TCPServer:
    """
A class that represents a server that performs TCP communication
    """
    def serve(self):
        """
Start the server
        """

        print("===Start the server===")

        try:
            #Generate socket
            server_socket = socket.socket()
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            #Assign socket to localhost port 8080
            server_socket.bind(("localhost", 8080))
            server_socket.listen(10)

            #Wait for a connection from the outside and establish a connection if there is a connection
            print("===Wait for a connection from the client===")
            (client_socket, address) = server_socket.accept()
            print(f"===The connection with the client is complete remote_address: {address} ===")

            #Get the data sent from the client
            request = client_socket.recv(4096)

            #Write the data sent from the client to a file
            with open("server_recv.txt", "wb") as f:
                f.write(request)

            #Get the response data to be sent to the client from the file
            with open("server_send.txt", "rb") as f:
                response = f.read()

            #Send a response to the client
            client_socket.send(response)

            #End communication
            client_socket.close()

        finally:
            print("===Stop the server.===")


if __name__ == '__main__':
    server = TCPServer()
    server.serve()

Let's also create a server_send.txt for return.

server_send.txt

HTTP/1.1 200 OK
Date: Wed, 28 Oct 2020 07:57:45 GMT
Server: Apache/2.4.41 (Unix)
Content-Location: index.html.en
Vary: negotiate
TCN: choice
Last-Modified: Thu, 29 Aug 2019 05:05:59 GMT
ETag: "2d-5913a76187bc0"
Accept-Ranges: bytes
Content-Length: 45
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

<html><body><h1>It works!</h1></body></html>

Try running the program

Move to the directory where the source code is placed on the console, and execute the program with the following command.

$ python TCPServer.py
===Start the server===
===Wait for a connection from the client===

Keep the console tab open and try accessing http: // localhost: 8080 in your browser.

スクリーンショット 2020-10-26 18.49.04.png

It was displayed as a web page safely!

Understand how a web server works

Except for comments, I was able to run a fairly primitive web server in just over a dozen lines. (At the moment, it is more accurate to call it a TCP server, not a white server that can be called a Web server ...)

The best way to understand how everything works is to make it yourself.

If you want to understand how a web server or web framework works, please come to our online book. https://zenn.dev/bigen1925/books/e6c9492a82f5e2e10fca/viewer/504d96 Please read!

There is also a description of the source code for this article.

Recommended Posts

Getting Started with Python Web Applications
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting Started with Python Functions
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Getting Started with Python for PHPer-Classes
Getting Started with Python Basics of Python
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Getting Started with Flask with Azure Web Apps
Getting Started with Python for PHPer-Super Basics
Getting started with Dynamo from Python boto
Django 1.11 started with Python3.6
Getting started with Android!
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
[FastAPI] Getting started with FastAPI, an ASGI web framework made by Python
Getting started with Python with 100 knocks on language processing
[Translation] Getting Started with Rust for Python Programmers
Introduction to Tornado (1): Python web framework started with Tornado
Getting started with AWS IoT easily in Python
Materials to read when getting started with Python
Settings for getting started with MongoDB in python
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Web scraping with python + JupyterLab
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Web API with Python + Falcon
Get started with Python! ~ ② Grammar ~
Getting Started with Django with PyCharm
Web application with Python + Flask ② ③
Web scraping beginner with python
Streamline web search with python
Web application with Python + Flask ④
Getting Started with Google App Engine for Python & PHP
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Web scraping with Python ① (Scraping prior knowledge)
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Web scraping with Python First step