4

python进阶打包部署docker

 1 year ago
source link: https://blog.shareworld.vip/archives/packaging-deploy
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python进阶打包部署docker

Owen Jia 2022年12月21日 1次浏览

目前了解下来python是没有打包构建可执行文件,类似java的flat jar概念的。我想这正和‘解释型语言’与‘编译型语言’的区别,.java文件先要编译.class文件才能执行,而.py直接即能执行。

所以在python的部署里,只要把工程文件全部copy或者zip下放到服务器上,再把python环境在服务器上安装好即可,对于有venv环境的,三方包已经在venv的site-packages下,所以理论上copy过去就能直接python app.py这般执行。

也支持类似nohup命令 nohup /bin/python3 app.py>/dev/null 2>&1 &是可行的,这个java -jar app.jar是一样。

http-server-docker

http-server-docker

特地借用python标准库中http包,写了一个简单的http服务器,这样就能保持服务一直拉起状态,方便测试。

import http.serverimport httpclass request_handle(http.server.SimpleHTTPRequestHandler): 自定义请求处理类 def do_GET(self): print('client_address', self.client_address) print('headers', self.headers) print('path', self.path) print("command:", self.command) self.send_response(200) self.wfile.write("i get your message by get".encode("utf-8")) def do_POST(self): print('client_address', self.client_address) print('headers', self.headers) print('path', self.path) print("command:", self.command) self.send_response(200) self.wfile.write("i get your message by post".encode("utf-8"))def my_server(): addr = "127.0.0.1" port = 8080 server_o = (addr, port) httpd = http.server.HTTPServer(server_o, request_handle) return httpddef info(): print('http...')if __name__ == '__main__': info() my_server().serve_forever()

通过命令curl http:/127.0.0.1:8080/test/ok测试。

另外像docker一样部署,也完全是与java一致,或者说docker部署可编程语言是解耦的,docker 的 cmd []命令只要拉起程序就行。

FROM python:3.9WORKDIR /appADD . /appRUN pip install -r requirements.txtCMD ["python","app.py"]

docker 部署启动,构建image起本质与服务器上直接python启动是相同的,只是对加了一个沙盒。

工程目录直接zip,然后在服务器上unzip,用python命令启动也挺快。有时候一个单文件的脚本.py的移动并可执行,真的是很方便。确实在这块来说,比java吸引人,特别是哪些只是作为一个脚本用的人来说。

学海无涯,苦作舟


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK