Skip to content

Flask服务Demo2

依赖环境

Dockerfile
FROM ubuntu:22.04

RUN sed -i 's/archive.ubuntu.com/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
RUN apt update

RUN apt install -y libpq-dev
RUN apt install -y python3.8 python3-pip python3-dev
RUN apt install -y make

RUN DEBIAN_FRONTEND=noninteractive TZ=Asia/Shanghai apt-get -y install tzdata
ENV TZ=Asia/Shanghai

RUN python3.8 -m pip install poetry -i https://pypi.tuna.tsinghua.edu.cn/simple
RUN ln -s /usr/bin/python3 /usr/bin/python
yml
version: '2'
services:
    web:
        build: .
        restart: always
        volumes:
          - .:/root/project
          - ./cache:/root/.cache/
        working_dir: /root/project
        command: poetry run python interface.py
        environment:
          - WEB_PORT=9000
        logging:
          driver: "json-file"
          options:
            max-size: "10000k"
            max-file: "10"
        network_mode: host
toml
[tool.poetry]
name = "project"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.8"
gevent = "^21.12.0"
Flask = "^2.2.2"
Flask-RESTful = "^0.3.9"
loguru = "^0.6.0"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Makefile
WORK_DIR    := /root/project

DOCKER_u2py := docker run --rm -it -v $(PWD):$(WORK_DIR) -v $(PWD)/cache:/root/.cache/ -w $(WORK_DIR) u2py

build:
	docker build . -t u2py
init:
	$(DOCKER_u2py) poetry init
install:
	$(DOCKER_u2py) poetry install
# add:
# 	$(DOCKER_u2py) poetry add loguru
run:
	$(DOCKER_u2py) poetry run python interface.py
test:
	$(DOCKER_u2py) poetry run python test.py

代码

python
from gevent import pywsgi
from flask import Flask, Blueprint, request
from flask_restful import Api, Resource
from loguru import logger
import os

logger.add("log/login.log", rotation="500MB")
app = Flask(__name__)

bp_server = Blueprint('api', __name__)
api = Api(bp_server)


class LoginItem(Resource):
    def post(self):
        d = request.json
        logger.info(d)
        logger.info(d.get('username'))
        return dict(code=200, msg="success")

api.add_resource(LoginItem, '/login')
app.register_blueprint(bp_server, url_prefix='/server')

def main():
    port = os.getenv('WEB_PORT')
    print('[+] API running on {}'.format(port))
    app.run(port=port, host="127.0.0.1", debug=True)
    # server = pywsgi.WSGIServer(('', port), app)
    # server.serve_forever()


if __name__ == "__main__":
    main()

Released under the MIT License.