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…

从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按层顺序构建模…