--The web is a client server system. Client → Server ** Request **. From server to client, open a TCP / IP connection, send URL and other information via HTTP, and receive ** response **. --The response has status, response data and format. --The most well-known web client is a web browser. You can send HTTP requests in a variety of ways.
--Each HTTP connection is independent and independent of other connections. (Stateless) → Cookies are used as a way to manage state instead of HTTP. --The server puts client-specific information in a cookie and sends it to the client. → When the client sends the cookie back to the server, the server uniquely identifies the client from the cookie.
Web clients and server modules weren't very well organized in Python 2. → In Python3, it is summarized in a package.
--http manages client server HTTP details. --client does client-side processing. --server helps develop web servers with Python. --Cookies and cookie jars manage cookies that store necessary information across multiple site visits.
--urllib runs on http. --request processes the client's request. --response processes the server response. --parse separates the URL into parts.
>>> import urllib.request as ur
>>> url="https://raw.githubusercontent.com/koki0702/introducing-python/master/dummy_api/fortune_cookie_random1.txt"
>>> conn=ur.urlopen(url)
>>> print(conn)
<http.client.HTTPResponse object at 0x10733c8d0>
>>> data=conn.read()
>>> print(data)
b'You will be surprised by a loud noise.\\r\\n\\n[codehappy] http://iheartquotes.com/fortune/show/20447\n'
#Display of HTTP status code.
#A 200 indicates that all the code worked.
>>> print(conn.status)
200
#Data format display
#Content in HTTP response header-Specified by Type.
>>> print(conn.getheader("Content-Type"))
text/plain; charset=utf-8
>>> for key,value in conn.getheaders():
... print(key,value)
...
Content-Type text/plain; charset=utf-8
Content-Security-Policy default-src 'none'; style-src 'unsafe-inline'; sandbox
Strict-Transport-Security max-age=31536000
X-Content-Type-Options nosniff
X-Frame-Options deny
X-XSS-Protection 1; mode=block
ETag W/"9f5651c47de1d25d4c531d22c98b96ea61d10d7e4f5c6eb6cbeecd9e01cdfbf8"
Cache-Control max-age=300
X-Geo-Block-List
Via 1.1 varnish-v4
X-GitHub-Request-Id D326:4317:329188:36E387:5E2EBEE7
Content-Length 99
Accept-Ranges bytes
Date Mon, 27 Jan 2020 10:43:52 GMT
Via 1.1 varnish
Connection close
X-Served-By cache-tyo19932-TYO
X-Cache MISS
X-Cache-Hits 0
X-Timer S1580121832.776951,VS0,VE269
Vary Authorization,Accept-Encoding, Accept-Encoding
Access-Control-Allow-Origin *
X-Fastly-Request-ID 034e4e0799a3de2ed0ae382d63bcd716a0574002
Expires Mon, 27 Jan 2020 10:48:52 GMT
Source-Age 0
>>>
--It is more convenient to use the requests of the third party module.
>>> import requests
>>> url="https://raw.githubusercontent.com/koki0702/introducing-python/master/dummy_api/fortune_cookie_random1.txt"
>>> resp=requests.get(url)
>>> resp
<Response [200]>
>>> print(resp.text)
I know that there are people who do not love their fellow man, and I people like that!
-- Tom Lehrer, Satirist and Professor
[codehappy] http://iheartquotes.com/fortune/show/21465
$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [27/Jan/2020 20:09:04] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Jan/2020 20:09:04] code 404, message File not found
127.0.0.1 - - [27/Jan/2020 20:09:04] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [27/Jan/2020 20:12:55] "GET /wheel HTTP/1.1" 200 -
q
C
^C
python -m http.server 9999
Serving HTTP on 0.0.0.0 port 9999 (http://0.0.0.0:9999/) ...
^C
--A web framework does more than a simple web server because it provides the functionality to create a website. The main functions are shown below. --Routing: Parses the URL and calls the server function. --Template: Stream server-side data into an HTML page.
python
#Other values can be specified for the port number.
python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
#127.0.0.1 :Client address
#The first- :Remote user name
#Second- :Login user name
#"GET / HTTP/1.1":Commands sent to the web server
#GET is an HTTP method,/Is the requested resource (root directory), HTTP/1.1 is the HTTP version.
#200:HTTP status code
127.0.0.1 - - [27/Jan/2020 20:09:04] "GET / HTTP/1.1" 200 -
9.2.2 WSGI A leap forward since the definition of WSGI, a universal API between Pytho web applications and web servers.
The web framework provides some or all of the following features:
--Routing
9.2.4 Bottle
--Bottle is made entirely of Python files, so it's very easy to try and deploy.
bottle installation
pip install bottle
Collecting bottle
Downloading bottle-0.12.18-py3-none-any.whl (89 kB)
|████████████████████████████████| 89 kB 692 kB/s
Installing collected packages: bottle
Successfully installed bottle-0.12.18
bottle1.py
from bottle import route, run
#To associate the URL with the function immediately following it@Use the route decorator.
#in this case,/(home page)Is processed by the home function.
@route("/")
def home():
return "It is not fancy, but it is my home page"
#run()The function runs a Python test web server built into bottle.
run(host="localhost",port=9999)
Execution statement
python3 bottle1.py
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:9999/
Hit Ctrl-C to quit.
Execution result
#http://localhost:Access 9999.
It is not fancy, but it is my home page
bottle2.py
#Make bottle return the contents of this file when the home page is requested.
from bottle import route, run, static_file
@route("/")
#Root indicates"."Is the current directory.
def home():
return static_file("index.html",root=".")
run(host="localhost",port=9999)
Execution statement
python bottle2.py
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:9999/
Hit Ctrl-C to quit.
Execution result
#http://localhost:9999/Access to.
My new and improved home page!!!
bottle3.py
from bottle import route, run, static_file
@route("/")
def home():
return static_file("index.html",root=".")
#Pass arguments to the function via the URL.
#echo()The argument thing of is in the URL/echo/Substitute the string argument after.
@route("/echo/<thing>")
def echo(thing):
return "Say hello to my little friend: %s" % thing
# debug=True
# reloader=True
run(host="localhost",port=9999)
Execution statement
python bottle3.py
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:9999/
Hit Ctrl-C to quit.
127.0.0.1 - - [27/Jan/2020 20:59:21] "GET /echo/Mothra HTTP/1.1" 200 37
Execution result
#http://localhost:9999/echo/Access Mothra.
Say hello to my little friend: Mothra
--If debug = True is specified, a debug page will be created when an HTTP error is returned. --If reloader = True, the page reloads in the browser when you make changes to your Python code.
9.2.5 Flask
--It's smarter than Bottle.
Flask installation
pip install flask
...
Successfully installed Jinja2-2.10.3 MarkupSafe-1.1.1 Werkzeug-0.16.1 click-7.0 flask-1.1.1 itsdangerous-1.1.0
--The default home directory for Flask static files is static, and URLs for files in that directory also start with / static. Therefore, the home directory is set to "." So that the URL / is mapped to the index.html file. --Set debug = True in the run () function to enable automatic reloading. bottle uses separate arguments for debugging and reloading. Also, when an exception occurs, Flask returns a specially formatted page with detailed information about where the problem occurred.
flask1.py
from flask import Flask
app=Flask(__name__, static_folder=".",static_url_path="")
@app.route("/")
def home():
return app.send_static_file("index.html")
@app.route("/echo/<thing>")
def echo(thing):
return thing
# reloader=True
app.run(port=9999, debug=True)
Execution result
#http://127.0.0.1:9999/Access to.
My new and improved home page!!!
#http://127.0.0.1:9999/echo/Enter Godzilla in your browser.
Godzilla
--Flask has a template called jinja2.
flask2.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Flask2 Example</title>
</head>
<body>
Say hello to my little friend:{{ thing }}
</body>
</html>>
flask2.py
from flask import Flask, render_template
app=Flask(__name__)
#thing=thing read from URL<thing>Is assigned to a variable called thing, and this is"flask2.html"Passed to.
@app.route("/echo/<thing>")
def echo(thing):
return render_template("flask2.html",thing=thing)
app.run(port=9999,debug=True)
Execution result
#http://127.0.0.1:9999/echo/Enter Gamera in your browser
< Say hello to my little friend:Gamera >
flask3.html
<html>
<head>
<title>Flask3 Example</title>
</head>
<body>
Say hello to my little friend: {{ thing }}.
Alas, in just destroyed {{ place }}!
</body>
</html>
flask3a.py
from flask import Flask, render_template
app=Flask(__name__)
@app.route("/echo/<thing>/<place>")
def echo(thing, place):
return render_template("flask3.html",thing=thing, place=place)
app.run(port=9999, debug=True)
Execution result
#http://127.0.0.1:9999/echo/Rodan/Visit McKeesport.
Say hello to my little friend: Rodan. Alas, in just destroyed McKeesport!
flask3b.py
from flask import Flask, render_template, request
app=Flask(__name__)
#Pass it as a GET argument.
@app.route("/echo/")
def echo():
thing=request.args.get("thing")
place=request.args.get("place")
return render_template("flask3.html",thing=thing, place=place)
app.run(port=9999, debug=True)
Execution result
#http://127.0.0.1:9999/echo/?thing=Gorgo&place=Visit Wilmerding.
Say hello to my little friend: Gorgo. Alas, in just destroyed Wilmerding!
flask3c.py
from flask import Flask, render_template, request
app=Flask(__name__)
@app.route("/echo/")
#Of the dictionary**Use to convert the key into a dictionary and falask3.Can be passed to html.
def echo():
kwargs={}
kwargs["thing"]=request.args.get("thing")
kwargs["place"]=request.args.get("place")
return render_template("flask3.html",**kwargs)
app.run(port=9999, debug=True)
--The following two web servers are used in the production system. --Apache with mod_wsgi module --nginx with uWSGI application server
There are many.
The web is used as a powerful way to connect applications and data in a variety of formats other than HTML.
--Web API can provide web page data --RESTful services use HTTP verbs in a fixed way. --HEAD: Get information about resources. --GET: Get resource data from the server. --POST: Update server data. --PUT: This verb creates a new resource. --DELETE: Delete
9.3.2 JSON
--Suitable for exchanging data between web clients and servers.
For some study. "Scrapy Tutorial" https://doc-ja-scrapy.readthedocs.io/ja/latest/intro/tutorial.html
--Beautiful Soup is useful if you have already retrieved the HTML and data from your website.
flask9-1.py
from flask import Flask
app=Flask(__name__)
app.run(port=5000, debug=True)
flask9-2.py
from flask import Flask
app=Flask(__name__)
@app.route("/")
def home():
return "It is alive"
app.run(port=5000, debug=True)
home.html
<html>
<head>
<title>It is alive!</title>
<body>
I am of course referring to {{thing}},which is {{height}} feet tall and {{color}}.
</body>
</html>
Pass three GET arguments, thing, height, and color, to the home () function.
flask9-4.py
from flask import Flask, render_template, request
app=Flask(__name__)
@app.route("/")
def home():
thing=request.args.get("thing")
height=request.args.get("height")
color=request.args.get("color")
return render_template("home.html",thing=thing, height=height, color=color)
app.run(port=5000, debug=True)
I reviewed the Web system quickly. Even if you use this area, it seems to be a long way off.
"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"
Recommended Posts