WSGI(Web Server Gateway Interface,web服务器网关接口)主要规定了服务器端和应用程序之间的接口,即规定了请求的URL到后台处理函数之间的映射该如何实现。wsgiref是一个帮助开发者开发测试的Python内置库,程序员可以通过这个库了解WSGI的基本运行原理,但是不能把它用在生产环境上。

WSGI处理过程
  1. 浏览器到wsgi server :浏览器发送的请求会先到wsgi server
  2. environ: wsgi server 会将http请求中的参数等信息封装到environ(一个字典) 中
  3. wsgi server 到wsgi app :app就是我们编写的后台程序,每个url会映射到对于的入口处理函数,wsig server调用后台app时,会将environ和wsgi server中自己一个start_response函数注入到后台app中
  4. 逻辑处理:后台函数需要接受environ和start_response,进行逻辑处理后返回一个可迭代对象,可迭代对下中的元素为http正文
  5. wsgi app 到wsgi server:后台函数处理完后,会先调用start_response函数将http状态码,报文头等信息(响应头)返回给wsgi server,然后再将函数的返回值作为http正文(响应body)返回给wsgi server.
  6. wsgi server 到浏览器:wsgi server 将从app中等到的所有信息封装作为一个response返回给浏览器
import hashlib,requests,json,time,urllib.parse
from http import HTTPStatus
import dashscope from wsgiref.simple_server import make_server errStr ='''
{
"code" : -1,
"msg" : "not support"
}
''' notStr = '''
{
"code" : -2,
"msg" : "not allowed"
}
''' # For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html dashscope.api_key="api_key" # 自己的api_key
def al(cont):
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '%s'%cont}] response = dashscope.Generation.call(
dashscope.Generation.Models.qwen_turbo,
messages=messages,
result_format='message', # set the result to be "message" format.
)
if response.status_code == HTTPStatus.OK:
content = response['output']['choices'][0]['message']['content']
# print(content)
return content
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
)) return errStr # 通义千问
def Tongyi(cont): url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
payload = json.dumps({
"model": "qwen-turbo",
"input": {
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": cont
}
]
},
"parameters": {}
})
headers = {
'Content-Type': 'application/json',
'Authorization': 'key' # 换成自己的key
} response = requests.request("POST", url, headers=headers, data=payload)
msg = response.json()['output']['text'] return msg # 青云客
def qingyunk(cont): url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s" % (urllib.parse.quote(cont)) html = requests.get(url)
msg = html.json()['content']
return msg def RunServer(environ,start_response):
# 添加回复内容的http头部信息,支持多个
headers = {'Content-Type': 'application/json', 'Custom-head1': 'Custom-info1'}
# environ 包含当前环境信息与请求信息,为字符串类型的键值对
current_url = environ['PATH_INFO']
current_content_length = environ['CONTENT_LENGTH']
current_request_method = environ['REQUEST_METHOD'] # 获取body json 内容转换为python对象
current_req_body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
current_req_json = json.loads(current_req_body)
# 获取输入值
cont = current_req_json['cont']
cont = urllib.parse.unquote(cont)
print(cont) #打印请求信息
print("REQUEST METHOD:",current_request_method)
print("REQUEST URL:",current_url)
print("REQUEST BODY:",current_req_json) #根据不同url回复不同内容
if current_url == "/qingyunk":
if current_request_method == "GET":
result = Tongyi(cont)
print(result)
# 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result) start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ]
else:
start_response('403 not allowed',list(headers.items()))
return [notStr.encode("utf-8"),]
elif current_url == "/Tongyi":
result = qingyunk(cont)
print(result)
# 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result) start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ]
elif current_url == '/al':
result = al(cont) # 拼装回复报文
successStr = '''
{
"code":200,
"msg":"success",
"data":{
"content":"%s"
}
}
''' % (result) start_response("200 OK", list(headers.items()))
return [successStr.encode("utf-8"), ] else:
start_response("404 not found", list(headers.items()))
return [errStr.encode("utf-8"), ] if __name__ == "__main__":
httpd = make_server('', 10000, RunServer)
host, port = httpd.socket.getsockname()
print('Serving running', host, 'port', port)
httpd.serve_forever()

WSGI web服务器

  • 本质上是一个TCP服务器,监听在特定的端口上。
  • 支持HTTP协议,能够解析HTTP请求报文,能够按HTTP协议将响应数据封装为报文并返回给浏览器。
  • 实现了WSGI协议,该协议约定了和应用程序之间的接口,即url到app之间的映射。

WSGI应用程序

  • 遵从WSGI协议。
  • 本身是一个可调用对象。
  • 调用start_response,返回响应头部。
  • 返回包含正文的可迭代对象。

python 搭建HTTP服务器的更多相关文章

  1. Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构

    用python搭建web服务器,与ajax交互,接收处理Get和Post请求:简单实用,没有用框架,适用于简单需求,更多功能可进行扩展. python有自带模块BaseHTTPServer.CGIHT ...

  2. python搭建简易服务器实例参考

    有关python搭建简易服务器的方法. 需求分析: 省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪, 每次打开都要缓上半天,甚至浏览器直接挂掉 采用python搭建一个最最简易的 w ...

  3. python搭建本地服务器

    python搭建本地服务器 python3以上版本 'python3 -m http.server 8000' 默认是8000端口,可以指定端口,打开浏览器输入http://127.0.0.1:800 ...

  4. [容器]python搭建简易服务器+docker导入多个镜像shell脚本

    从其他机器导出来的docker镜像,集中地放在某台上,其他的机器执行 curl xxx:8000/load_images.sh 来导入镜像,简单方便 使用python简易web服务器. (在镜像目录下 ...

  5. 使用Python搭建http服务器

    David Wheeler有一句名言:“计算机科学中的任何问题,都可以通过加上另一层间接的中间层解决.”为了提高Python网络服务的可移植性,Python社区在PEP 333中提出了Web服务器网关 ...

  6. python 搭建http服务器和ftp服务器

    默认安装版本为pytho2.7 http服务器搭建: 进入要开放访问的目录下,执行命令:python -m SimpleHTTPServer 9000 显示上述表示安装成功,且http服务的端口为:9 ...

  7. python 搭建ftp服务器

    代码示例: # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.han ...

  8. python搭建ftp服务器

    1 # coding: utf-8 import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handler ...

  9. Python一秒搭建ftp服务器,帮助你在局域网共享文件【华为云技术分享】

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/devcloud/article/detai ...

  10. Python一秒搭建ftp服务器,帮助你在局域网共享文件

    "老板 来碗面" "要啥面?" "内牛满面.." 最近项目上的事情弄得人心累,本来是帮着兄弟项目写套入口代码,搞着搞着就被拉着入坑了.搞开发 ...

随机推荐

  1. Python 数据库应用教程:安装 MySQL 及使用 MySQL Connector

    Python可以用于数据库应用程序. 其中最流行的数据库之一是MySQL. MySQL数据库 为了能够在本教程中尝试代码示例,您应该在计算机上安装MySQL. 您可以在 MySQL官方网站 下载MyS ...

  2. Doxygen 的学习

    https://dongzhixiao.blog.csdn.net/article/details/52190696 来自转载

  3. Lyndon 分解

    介绍 [模板]Lyndon 分解 #include<cstdio> #include<cstring> char s[5000005]; int main(){ scanf(& ...

  4. 发现AI自我意识:从理解到思维

    广义"理解"已经实现 在最新的人工智能系统中,我们经常可以观察到一种类似"理解"的能力.这种广义的"理解"能力,主要建立在两个基础之上:海量 ...

  5. 使用reposync工具将yum安装包保存到本地的方法

    使用reposync工具将yum安装包保存到本地的方法 版权声明:原创作品,谢绝转载!否则将追究法律责任. ----- 作者:kirin Anolis7/centos7 1.reposync 1.1. ...

  6. crm系统功能有哪些?

    CRM系统是指客户关系管理系统,其核心理念是将客户视为企业的宝贵资源,为了最大化地发掘和利用客户价值,运用各种先进的技术与方法来促进商业活动中所有涉及到客户的流程和业务,所以实际上CRM系统也是一个综 ...

  7. VM离线安装Centos 8以及配置

    一.安装 1.预装准备 1.1. 硬件准备 物理内存:2G以上(这里指系统搭建所需占用空间) 物理外存:20G(这里指系统搭建所需占用空间) 1.2. 环境搭建准备 Window10系统电脑一台.Vm ...

  8. SnagIt 9-12 注册码

    SnagIt 9 注册码: AM5SC-8LWML-MVMWU-DTLGE-ERMBE SnagIt 10 注册码: 5HCAK-DEGMZ-EYABA-M4LCC-ACBE2DFKDA-JZ5FC- ...

  9. Http请求超好用的工具类

    话题不多说,直接开整 1.先导入依赖 <dependency> <groupId>io.github.admin4j</groupId> <artifactI ...

  10. 微服务项目-小Q视频网

    1.后台管理系统(更新中...) (1)讲师列表 (2)添加讲师 (3)导入课程分类 (4)课程分类列表 其他功能就不一一截图了,后台详细功能如下 2.前台会员系统(更新中...) (1)前台的技术栈 ...