PythonAnyWhere免费部署python API

1 介绍

本篇文章介绍如何使用 PythonAnyWhere 来部署python API 服务。

2 使用方法

2.1 申请免费的PythonAnyWhere账号

网址:https://www.pythonanywhere.com/ 免费的账号只能建一个站

2.2 将GitHub上的项目发送至PythonAnyWhere

1 在PythonAnyWhere中,点击 “Consoles” –> start a “Bash” console
这个Bash是类似于Linux系统里的“终端”。
2 在这个新建的Bash里面输入:
注意:如下代码表示需要在PythonAnyWhere的Bash中执行!!

1
$ git clone https://github.com/<your-github-username>/my-flask-api.git

2.3 发布Web App

在PythonAnyWhere里,点击 “Web”选项卡 -> 点击 “Add a new web app”
-> 确认域名 -> 选择manual configuration(注意不是选择“Django”哦) -> 选择Python3.8 -> 点击Next以最终完成向导。

2.4 配置PythonAnyWhere里的WSGI文件

仍然是在Web选项卡,点击WSGI configuration file后面的蓝色字体连接(如下图所示)。
PythonAnyWhere将带我们到一个新的页面(一个代码编辑器),将编辑器的代码全部用下面的代码替换。

1
2
3
4
5
6
7
8
9
import sys

# add your project directory to the sys.path
project_home = '/home/<你的PythonAnyWhere用户名>/my-flask-api'
if project_home not in sys.path:
sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from app import app as application # noqa

点击 “Save” -> 返回Web选项卡 -> 点击大大的绿色按钮“Reload”。此时我们就可以通过Web选项卡上提供的地址(也就是XXX.pythonanywhere.com)访问了!