web.py启动https端口需要ssl证书,如果没有ssl证书,那么可以通过如下方式生成。
openssl genrsa -des3 -out server.key 1024 openssl req -new -key server.key -out server.csr openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt sudo openssl rsa -in server.key -out server.key
示例程序如下所示:
# -*- coding: utf-8 -*- """ Created on Mon May 10 20:37:00 2021 @author: Administrator """ import web #web.py urls = ( '/server' , 'server', '/.*', 'notfound' #localhost:port/其他任意界面,访问notfound类 ) class MyApplication(web.application): def run(self, port=8080, *middleware): func = self.wsgifunc(*middleware) return web.httpserver.runsimple(func, ('0.0.0.0', port)) class server: def __init__(self): self.return_msg = {'errorCode': 0, 'msg': '系统正常!'} def POST(self): #POST处理方式与GET一致 # content = web.input() # print('收到消息:', content.key1, content.key2, content.key3) x = web.input(myfile={}) print('xxx: ', x.keys()) return str(self.return_msg).replace('\'', '\"') class notfound: def GET(self): print('--from notfound') return '404 not found' def POST(self): print('--from notfound') return '404 not found' from cheroot.server import HTTPServer from cheroot.ssl.builtin import BuiltinSSLAdapter HTTPServer.ssl_adapter = BuiltinSSLAdapter( certificate='server.crt', private_key='server.key') if __name__ == "__main__": app = MyApplication(urls ,globals()) app.run(port=443)
第一步:在shell中依次执行以下命令,回答问题,设置密码生成证书,包含三个文件***.crt 和***.key和***.csr,我分别重新命令为server.crt server.csr server.key
openssl genrsa -des3 -out server.key 1024 openssl req -new -key server.key -out server.csr openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt mv server.key myserver.key mv server.crt myserver.crt
开启服务,仿照下面代码输入即可,其中
from handle import Handle引入的我的方法模块,在urls中调用(仿照微信公众号开发的例子,具体如果新手可以自己看),同时保存的文件路径根据自己的写
import web from handle import Handle from web.wsgiserver import CherryPyWSGIServer CherryPyWSGIServer.ssl_certificate = "/usr/ssl/server.crt" CherryPyWSGIServer.ssl_private_key = "/usr/ssl/server.key" urls = ( '/wx', 'Handle', ) if __name__ == '__main__': app = web.application(urls, globals()) app.run()
然后开始服务 sudo python main.py 443(其中443是端口号)
这个时候你需要输入ssl之前自己设置的密码,才能开启,但是这样导致不能后台隐藏,
但是在生成证书的文件夹下,执行sudo openssl rsa -in server.key -out server.key即可无密码,这样就可以后台执行
nohup python main.py 443 &
以上是python web.py怎么启动https端口的详细内容。更多信息请关注PHP中文网其他相关文章!