02-web框架

1

while True:print('server is waiting...')conn, addr = server.accept()data = conn.recv(1024)          print('data:', data)# 1.得到請求的url路徑# ------------dict/obj   d=["path":"/login"]# d.get(”path“)# 按著http請求協議解析數據# 專注于web業務開發path = d.get('path')if path == "/login":return login.html# 按著http響應協議封裝數據

?

2

# 報錯信息
C:\Windows\system32>pip install wsgiref
Collecting wsgirefUsing cached https://files.pythonhosted.org/packages/41/9e/309259ce8dff8c596e8c26df86dbc4e848b9249fd36797fd60be456f03fc/wsgiref-0.1.2.zipComplete output from command python setup.py egg_info:Traceback (most recent call last):File "<string>", line 1, in <module>File "C:\Users\Venicid\AppData\Local\Temp\pip-build-f8zmzqr9\wsgiref\setup.py", line 5, in <module>import ez_setupFile "C:\Users\Venicid\AppData\Local\Temp\pip-build-f8zmzqr9\wsgiref\ez_setup\__init__.py", line 170print "Setuptools version",version,"or greater has been installed."^SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Setuptools version",version,"or greater has been installed.")?----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Venicid\AppData\Local\Temp\pip-build-f8zmzqr9\wsgiref\

?

  

# wsgiref 是標準庫,不需要安裝C:\Windows\system32>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC 
>>> import wsgiref

  

?

from wsgiref.simple_server import make_serverdef application(environ,start_response):# 按著http協議解析數據:environ# 按著http協議組裝數據:start_responseprint(environ)print(type(environ))start_response('200 OK', [])return [b"<h3>hello wsgiref</h3>"]# 1.封裝socket
httpd = make_server("",8802,application)# 2.等待用戶連接: conn,addr = server.accept()
httpd.serve_forever()       # application(environ,start_response)

?

?

?

?

?根據path進行響應不同的html

?

方案1:

from wsgiref.simple_server import make_serverdef application(environ,start_response):# 按著http協議解析數據:environ# 按著http協議組裝數據:start_responseprint(environ)print(type(environ))# 當前的請求路徑path = environ.get('PATH_INFO')print(path)start_response('200 OK', [])if path == "/login":with open('login.html','r') as f:data = f.read()elif path == '/index':with open('index.html','r') as f:data = f.read()elif path == '/favicon.ico':   # icon圖標with open('favicon.ico','rb') as f:data = f.read()return [data]return [data.encode('utf8')]# 1.封裝socket
httpd = make_server("",8802,application)# 2.等待用戶連接: conn,addr = server.accept()
httpd.serve_forever()       # application(environ,start_response)

?

?方案2:解耦

from wsgiref.simple_server import make_serverdef login():with open('login.html', 'rb') as f:data = f.read()return datadef index():with open('index.html', 'rb') as f:data = f.read()return datadef favi():with open('favicon.ico', 'rb') as f:data = f.read()return datadef application(environ, start_response):# 按著http協議解析數據:environ# 按著http協議組裝數據:start_responseprint(environ)print(type(environ))# 當前的請求路徑path = environ.get('PATH_INFO')start_response('200 OK', [])url_patterns = [("/login",login),('/index',index),('/favicon.ico',favi)]func = Nonefor item in url_patterns:if path == item[0]:func = item[1]breakif func:return [func()]else:return [b'404']# 1.封裝socket
httpd = make_server("", 8805, application)# 2.等待用戶連接: conn,addr = server.accept()
httpd.serve_forever()  # application(environ,start_response)

?

?

?

添加新的reg模塊:快速方便

?

?

?

?

?

?

?

?

  添加請求environ

from wsgiref.simple_server import make_serverdef login(environ):with open('login.html', 'rb') as f:data = f.read()return datadef index(environ):with open('index.html', 'rb') as f:data = f.read()return datadef reg(environ):with open('reg.html', 'rb') as f:data = f.read()return datadef favi(environ):with open('favicon.ico', 'rb') as f:data = f.read()return datadef application(environ, start_response):# 按著http協議解析數據:environ# 按著http協議組裝數據:start_responseprint(environ)print(type(environ))# 當前的請求路徑path = environ.get('PATH_INFO')start_response('200 OK', [])url_patterns = [("/login",login),('/index',index),('/favicon.ico',favi),('/reg',reg)]func = Nonefor item in url_patterns:if path == item[0]:func = item[1]breakif func:return [func(environ)]else:return [b'404']# 1.封裝socket
httpd = make_server("", 8805, application)# 2.等待用戶連接: conn,addr = server.accept()
httpd.serve_forever()  # application(environ,start_response)

?

?

?

?

3、yun框架

?

main.py 啟動程序

from wsgiref.simple_server import make_serverdef application(environ, start_response):path = environ.get('PATH_INFO')start_response('200 OK', [])from urls import url_patterns    # 導入路由表
func = Nonefor item in url_patterns:if path == item[0]:func = item[1]breakif func:result = func(environ)      # 執行視圖函數return [result]else:return [b'404']print('start yun框架...')# 1.封裝socket
httpd = make_server("", 8806, application)# 2.等待用戶連接: conn,addr = server.accept()
httpd.serve_forever()  # application(environ,start_response)

?

?

urls.py路由分發

from views import *url_patterns = [("/login", login),      # 視圖函數('/index', index),('/favicon.ico', fav),('/reg', reg),('/timer', timer)
]

?

?

views.py 視圖函數

def login(environ):with open('./templates/login.html', 'rb') as f:data = f.read()return datadef index(environ):with open('./templates/index.html', 'rb') as f:data = f.read()return datadef reg(environ):with open('./templates/reg.html', 'rb') as f:data = f.read()return datadef fav(environ):with open('./templates/favicon.ico', 'rb') as f:data = f.read()return datadef timer(environ):import datetimenow_time = datetime.datetime.now().strftime('%y-%m-%d %X')return now_time.encode('utf8')     # bytes類型

?

?

?

4、

新建 models.py 數據交換py文件

# 數據庫交互文件# 生成用戶表
import pymysql# 連接數據庫
conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='root',db='db61',charset='utf8'
)# 獲取游標
cursor = conn.cursor()# 執行sql語句
sql = """
create table userinfo(id int primary key,name varchar(32),password varchar(32)
)
"""
cursor.execute(sql)# 提交
conn.commit()# 關閉
cursor.close()
conn.close()

?

?

插入一個username ?password

?

views.py中的auth函數

def auth(request):from urllib.parse import parse_qs   # 分割取參數try:request_body_size = int(request.get('CONTENT_LENGTH',0))except (ValueError):request_body_size = 0request_body = request['wsgi.input'].read(request_body_size)data = parse_qs(request_body)user = data.get(b'username')[0].decode('utf8')pwd = data.get(b'password')[0].decode('utf8')# 連接數據庫import pymysqlconn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='db61',charset='utf8')# 創建游標cursor = conn.cursor()# 執行sqlsql = "select * from userinfo where name='%s' and password='%s'" % (user, pwd)cursor.execute(sql)if cursor.fetchone():   # 執行成功,返回一條信息result = index(request)   # 登錄成功,進入index頁面return resultelse:return 'Error username or passwrod'.encode('utf8')

?

?

?

?

?

5、總結

?

?

轉載于:https://www.cnblogs.com/venicid/p/9231549.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389362.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389362.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389362.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ai驅動數據安全治理_AI驅動的Web數據收集解決方案的新起點

ai驅動數據安全治理Data gathering consists of many time-consuming and complex activities. These include proxy management, data parsing, infrastructure management, overcoming fingerprinting anti-measures, rendering JavaScript-heavy websites at scale, and muc…

從Text文本中讀值插入到數據庫中

/// <summary> /// 轉換數據&#xff0c;從Text文本中導入到數據庫中 /// </summary> private void ChangeTextToDb() { if(File.Exists("Storage Card/Zyk.txt")) { try { this.RecNum.Visibletrue; SqlCeCommand sqlCreateTable…

Dataset和DataLoader構建數據通道

重點在第二部分的構建數據通道和第三部分的加載數據集 Pytorch通常使用Dataset和DataLoader這兩個工具類來構建數據管道。 Dataset定義了數據集的內容&#xff0c;它相當于一個類似列表的數據結構&#xff0c;具有確定的長度&#xff0c;能夠用索引獲取數據集中的元素。 而D…

鐵拳nat映射_鐵拳如何重塑我的數據可視化設計流程

鐵拳nat映射It’s been a full year since I’ve become an independent data visualization designer. When I first started, projects that came to me didn’t relate to my interests or skills. Over the past eight months, it’s become very clear to me that when cl…

Django2 Web 實戰03-文件上傳

作者&#xff1a;Hubery 時間&#xff1a;2018.10.31 接上文&#xff1a;接上文&#xff1a;Django2 Web 實戰02-用戶注冊登錄退出 視頻是一種可視化媒介&#xff0c;因此視頻數據庫至少應該存儲圖像。讓用戶上傳文件是個很大的隱患&#xff0c;因此接下來會討論這倆話題&#…

BZOJ.2738.矩陣乘法(整體二分 二維樹狀數組)

題目鏈接 BZOJ洛谷 整體二分。把求序列第K小的樹狀數組改成二維樹狀數組就行了。 初始答案區間有點大&#xff0c;離散化一下。 因為這題是一開始給點&#xff0c;之后詢問&#xff0c;so可以先處理該區間值在l~mid的修改&#xff0c;再處理詢問。即二分標準可以直接用點的標號…

從數據庫里讀值往TEXT文本里寫

/// <summary> /// 把預定內容導入到Text文檔 /// </summary> private void ChangeDbToText() { this.RecNum.Visibletrue; //建立文件&#xff0c;并打開 string oneLine ""; string filename "Storage Card/YD" DateTime.Now.…

DengAI —如何應對數據科學競賽? (EDA)

了解機器學習 (Understanding ML) This article is based on my entry into DengAI competition on the DrivenData platform. I’ve managed to score within 0.2% (14/9069 as on 02 Jun 2020). Some of the ideas presented here are strictly designed for competitions li…

Pytorch模型層簡單介紹

模型層layers 深度學習模型一般由各種模型層組合而成。 torch.nn中內置了非常豐富的各種模型層。它們都屬于nn.Module的子類&#xff0c;具備參數管理功能。 例如&#xff1a; nn.Linear, nn.Flatten, nn.Dropout, nn.BatchNorm2d nn.Conv2d,nn.AvgPool2d,nn.Conv1d,nn.Co…

有效溝通的技能有哪些_如何有效地展示您的數據科學或軟件工程技能

有效溝通的技能有哪些What is the most important thing to do after you got your skills to be a data scientist? It has to be to show off your skills. Otherwise, there is no use of your skills. If you want to get a job or freelance or start a start-up, you ha…

java.net.SocketException: Software caused connection abort: socket write erro

場景&#xff1a;接口測試 編輯器&#xff1a;eclipse 版本&#xff1a;Version: 2018-09 (4.9.0) testng版本&#xff1a;TestNG version 6.14.0 執行testng.xml時報錯信息&#xff1a; 出現此報錯原因之一&#xff1a;網上有人說是testng版本與eclipse版本不一致造成的&#…

[博客..配置?]博客園美化

博客園搞定時間 -> 18年6月27日 [讓我歇會兒 搞這個費腦子 代碼一個都看不懂] 轉載于:https://www.cnblogs.com/Steinway/p/9235437.html

使用K-Means對美因河畔法蘭克福的社區進行聚類

介紹 (Introduction) This blog post summarizes the results of the Capstone Project in the IBM Data Science Specialization on Coursera. Within the project, the districts of Frankfurt am Main in Germany shall be clustered according to their venue data using t…

Pytorch損失函數losses簡介

一般來說&#xff0c;監督學習的目標函數由損失函數和正則化項組成。(Objective Loss Regularization) Pytorch中的損失函數一般在訓練模型時候指定。 注意Pytorch中內置的損失函數的參數和tensorflow不同&#xff0c;是y_pred在前&#xff0c;y_true在后&#xff0c;而Ten…

讀取Mc1000的 唯一 ID 機器號

先引用Symbol.ResourceCoordination 然后引用命名空間 using System;using System.Security.Cryptography;using System.IO; 以下為類程序 /// <summary> /// 獲取設備id /// </summary> /// <returns></returns> public static string GetDevi…

樣本均值的抽樣分布_抽樣分布樣本均值

樣本均值的抽樣分布One of the most important concepts discussed in the context of inferential data analysis is the idea of sampling distributions. Understanding sampling distributions helps us better comprehend and interpret results from our descriptive as …

玩轉ceph性能測試---對象存儲(一)

筆者最近在工作中需要測試ceph的rgw&#xff0c;于是邊測試邊學習。首先工具采用的intel的一個開源工具cosbench&#xff0c;這也是業界主流的對象存儲測試工具。 1、cosbench的安裝&#xff0c;啟動下載最新的cosbench包wget https://github.com/intel-cloud/cosbench/release…

[BZOJ 4300]絕世好題

Description 題庫鏈接 給定一個長度為 \(n\) 的數列 \(a_i\) &#xff0c;求 \(a_i\) 的子序列 \(b_i\) 的最長長度&#xff0c;滿足 \(b_i\wedge b_{i-1}\neq 0\) &#xff08; \(\wedge\) 表示按位與&#xff09; \(1\leq n\leq 100000\) Solution 令 \(f_i\) 為二進制第 \(i…

因果關系和相關關系 大數據_數據科學中的相關性與因果關系

因果關系和相關關系 大數據Let’s jump into it right away.讓我們馬上進入。 相關性 (Correlation) Correlation means relationship and association to another variable. For example, a movement in one variable associates with the movement in another variable. For…

Pytorch構建模型的3種方法

這個地方一直是我思考的地方&#xff01;因為學的代碼太多了&#xff0c;構建的模型各有不同&#xff0c;這里記錄一下&#xff01; 可以使用以下3種方式構建模型&#xff1a; 1&#xff0c;繼承nn.Module基類構建自定義模型。 2&#xff0c;使用nn.Sequential按層順序構建模…