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.mzph.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…

铁拳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…

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…

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版本不一致造成的&#…

使用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…

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

样本均值的抽样分布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…

因果关系和相关关系 大数据_数据科学中的相关性与因果关系

因果关系和相关关系 大数据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…

vue取数据第一个数据_我作为数据科学家的第一个月

vue取数据第一个数据A lot.很多。 I landed my first job as a Data Scientist at the beginning of August, and like any new job, there’s a lot of information to take in at once.我于8月初找到了数据科学家的第一份工作&#xff0c;并且像任何新工作一样&#xff0c;一…

STL-开篇

基本概念 STL&#xff1a; Standard Template Library&#xff0c;标准模板库 定义&#xff1a; c引入的一个标准类库 特点&#xff1a;1&#xff09;数据结构和算法的 c实现&#xff08; 采用模板类和模板函数&#xff09;2&#xff09;数据的存储和算法的分离3&#xff09;高…

rcp rapido_为什么气流非常适合Rapido

rcp rapidoBack in 2019, when we were building our data platform, we started building the data platform with Hadoop 2.8 and Apache Hive, managing our own HDFS. The need for managing workflows whether it’s data pipelines, i.e. ETL’s, machine learning predi…

Mysql5.7开启远程

2019独角兽企业重金招聘Python工程师标准>>> 1.注掉bind-address #bind-address 127.0.0.1 2.开启远程访问权限 grant all privileges on *.* to root"xxx.xxx.xxx.xxx" identified by "密码"; 或 grant all privileges on *.* to root"%…

分类结果可视化python_可视化分类结果的另一种方法

分类结果可视化pythonI love good data visualizations. Back in the days when I did my PhD in particle physics, I was stunned by the histograms my colleagues built and how much information was accumulated in one single plot.我喜欢出色的数据可视化。 早在我获得…

算法组合 优化算法_算法交易简化了风险价值和投资组合优化

算法组合 优化算法Photo by Markus Spiske (left) and Jamie Street (right) on UnsplashMarkus Spiske (左)和Jamie Street(右)在Unsplash上的照片 In the last post, we saw how actual algorithms are developed and tested. In this post, we will figure out the level of…

PS抠发丝技巧 「选择并遮住…」

PS抠发丝技巧 「选择并遮住…」 现在的海报设计&#xff0c;大多数都有模特MM&#xff0c;然而MM的头发实用太多了&#xff0c;有的还飘起来…… 对于设计师(特别是淘宝美工)没有一个强大、快速、实用的抠发丝技巧真的混不去哦。而PS CC 2017版本开始&#xff0c;就有了一个强大…

covid 19如何重塑美国科技公司的工作文化

未来 &#xff0c; 技术 &#xff0c; 观点 (Future, Technology, Opinion) Who would have thought that a single virus would take down the whole world and make us stay inside our homes? A pandemic wave that has altered our lives in such a way that no human (bi…

python生日悖论分析_生日悖论

python生日悖论分析If you have a group of people in a room, how many do you need to for it to be more likely than not, that two or more will have the same birthday?如果您在一个房间里有一群人&#xff0c;那么您需要多少个才能使两个或两个以上的人有相同的生日&a…

rstudio 管道符号_R中的管道指南

rstudio 管道符号R基础知识 (R Fundamentals) Data analysis often involves many steps. A typical journey from raw data to results might involve filtering cases, transforming values, summarising data, and then running a statistical test. But how can we link al…

蒙特卡洛模拟预测股票_使用蒙特卡洛模拟来预测极端天气事件

蒙特卡洛模拟预测股票In a previous article, I outlined the limitations of conventional time series models such as ARIMA when it comes to forecasting extreme temperature values, which in and of themselves are outliers in the time series.在上一篇文章中 &#…

直方图绘制与直方图均衡化实现

一&#xff0c;直方图的绘制 1.直方图的概念&#xff1a; 在图像处理中&#xff0c;经常用到直方图&#xff0c;如颜色直方图、灰度直方图等。 图像的灰度直方图就描述了图像中灰度分布情况&#xff0c;能够很直观的展示出图像中各个灰度级所 占的多少。 图像的灰度直方图是灰…