Sanic server demo (in Ubuntu)
准备环境
shell
sudo apt install -y podman make python3-pip
pip3 install podman-compose
依赖环境
md
# Ubuntu22.04 Python3.10
::: code-group
```Dockerfile [Dockerfile]
FROM ubuntu:22.04
RUN sed -i 's/archive.ubuntu.com/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
# RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
RUN apt update
RUN apt install -y python3 python3-pip python3-dev
RUN apt install -y make
# for pgsql
# RUN apt install -y libpq-dev
RUN DEBIAN_FRONTEND=noninteractive TZ=Asia/Shanghai apt-get -y install tzdata
ENV TZ=Asia/Shanghai
RUN python3 -m pip install poetry -i https://pypi.tuna.tsinghua.edu.cn/simple
RUN ln -s /usr/bin/python3 /usr/bin/python
```
```Makefile [Makefile]
IMAGE_TAG := u22p310
WORK_DIR := /root/project
CACHE_DIR := /root/.cache
OUT_WORK_DIR := $(PWD)/project
OUT_CACHE_DIR := $(PWD)/__env_cache__
DOCKER_RUN := docker run \
--rm -it \
-v $(OUT_WORK_DIR):$(WORK_DIR) \
-v $(OUT_CACHE_DIR):$(CACHE_DIR) \
-w $(WORK_DIR) \
$(IMAGE_TAG)
build:
@docker build . -t $(IMAGE_TAG)
bash:
@$(DOCKER_RUN) /bin/bash
version:
@$(DOCKER_RUN) poetry run python -V
init:
@$(DOCKER_RUN) poetry init
install:
@$(DOCKER_RUN) poetry install --no-root
add:
@$(DOCKER_RUN) poetry add $(name)
remove:
@$(DOCKER_RUN) poetry remove $(name)
run:
@$(DOCKER_RUN) poetry run python $(name)
```
```shell [shell]
make version
# Python 3.10.12
```
:::
toml
[tool.poetry.dependencies]
python = "^3.10"
sanic = "^23.6.0"
yml
version: '3'
services:
interface:
build: .
image: upy2204
restart: always
volumes:
- .:/root/project
- ./cache:/root/.cache/
working_dir: /root/project
command: poetry run python app.py
environment:
- WEB_PORT=8488
logging:
driver: "json-file"
options:
max-size: "1000k"
max-file: "10"
network_mode: host
Makefile
WORK_DIR := /root/project
CACHE_DIR := /root/.cache
IMAGE_TAG := upy2204
PODMAN_RUN := podman run \
--rm -it \
-v $(PWD):$(WORK_DIR) \
-v $(PWD)/cache:$(CACHE_DIR) \
-w $(WORK_DIR) \
--net=host \
$(IMAGE_TAG)
build:
podman build . -t $(IMAGE_TAG)
bash:
@$(PODMAN_RUN) /bin/bash
python:
@$(PODMAN_RUN) python
init:
@$(PODMAN_RUN) poetry init
install:
@$(PODMAN_RUN) poetry install
add:
@$(PODMAN_RUN) poetry add ${name}
remove:
@$(PODMAN_RUN) poetry remove ${name}
run:
@$(PODMAN_RUN) poetry run python $(name)
up:
podman-compose up -d && podman-compose logs -f
down:
podman-compose down
logs:
podman-compose logs -f
ps:
podman ps -a
代码
python
from sanic import Sanic, Request
from sanic.response import json as resp_json
app = Sanic("app")
SECRET = 'aaaaaaaaaaaaaaaaaaaaa'
@app.get("/data")
async def data(r: Request):
return resp_json({"message": "success"}, status=200)
if __name__ == '__main__':
app.run(host="127.0.0.1", port=8488, access_log=True, auto_reload=True)
启动
shell
make build
make install
make up