先去参考:
使用 Python 和 Flask 设计 RESTful API — Designing a RESTful API with Python and Flask 1.0 documentation
->
-》
Designing a RESTful API using Flask-RESTful – miguelgrinberg.com
-》
REST-tutorial/rest-server-v2.py at master · miguelgrinberg/REST-tutorial · GitHub
Implementing a RESTful Web API with Python & Flask
去折腾。
参考:
去创建虚拟环境
➜ ~ mkvirtualenv RunningFast New python executable in /root/Envs/RunningFast/bin/python Installing setuptools, pip, wheel…done. virtualenvwrapper.user_scripts creating /root/Envs/RunningFast/bin/predeactivate virtualenvwrapper.user_scripts creating /root/Envs/RunningFast/bin/postdeactivate virtualenvwrapper.user_scripts creating /root/Envs/RunningFast/bin/preactivate virtualenvwrapper.user_scripts creating /root/Envs/RunningFast/bin/postactivate virtualenvwrapper.user_scripts creating /root/Envs/RunningFast/bin/get_env_details (RunningFast) ➜ ~ mkdir RunningFast (RunningFast) ➜ ~ cd RunningFast (RunningFast) ➜ RunningFast ll total 0 (RunningFast) ➜ RunningFast pwd /root/RunningFast |
参考:
去安装Flask
(RunningFast) ➜ RunningFast pip install flask Collecting flask Using cached Flask-0.11.1-py2.py3-none-any.whl Collecting itsdangerous>=0.21 (from flask) Collecting Jinja2>=2.4 (from flask) Using cached Jinja2-2.8-py2.py3-none-any.whl Collecting Werkzeug>=0.7 (from flask) Downloading Werkzeug-0.11.11-py2.py3-none-any.whl (306kB) 100% |████████████████████████████████| 307kB 7.0kB/s Collecting click>=2.0 (from flask) Collecting MarkupSafe (from Jinja2>=2.4->flask) Installing collected packages: itsdangerous, MarkupSafe, Jinja2, Werkzeug, click, flask Successfully installed Jinja2-2.8 MarkupSafe-0.23 Werkzeug-0.11.11 click-6.6 flask-0.11.1 itsdangerous-0.24 |
参考:
[记录]尝试将Nginx请求转到gunicorn运行的Flask
去安装gunicorn
(RunningFast) ➜ RunningFast pip install gunicorn Collecting gunicorn Using cached gunicorn-19.6.0-py2.py3-none-any.whl Installing collected packages: gunicorn Successfully installed gunicorn-19.6.0 |
然后此处打算让Flask运行在本地的21084端口
所以需要去更新nginx的配置
参考:
[已解决]Flask中用gunicorn和Nginx出错:502 Bad Gateway
去看看当前配置:
(RunningFast) ➜ RunningFast cat /etc/nginx/conf.d/default.conf server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/log/host.access.log main; location / { proxy_pass http://127.0.0.1:8080/; #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header X-Forwarded-Proto $scheme; } #location / { # root /usr/share/nginx/html; # index index.html index.htm; #} #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache’s document root # concurs with nginx’s one # #location ~ /\.ht { # deny all; #} } |
->
怎么感觉好像是:
对于此处的Flask的Restful的api来说:
好像不需要设置nginx的转发?
因为直接访问了api接口了?
去试试
最后解决了:
现在已经可以:
启动Flask服务:
gunicorn -w 4 -b 0.0.0.0:21084 run:app & |
外网可以访问了:
然后试了试PyCharm中的restful的api测试工具:
另外也去:
【已解决】PyCharm自动上传改动更新后的文件到CentOS服务器上
再去安装:flask-httpauth
(RunningFast) ➜ RunningFast pip install flask-httpauth Collecting flask-httpauth Downloading Flask-HTTPAuth-3.2.1.tar.gz Requirement already satisfied (use –upgrade to upgrade): Flask in /root/Envs/RunningFast/lib/python2.7/site-packages (from flask-httpauth) Requirement already satisfied (use –upgrade to upgrade): itsdangerous>=0.21 in /root/Envs/RunningFast/lib/python2.7/site-packages (from Flask->flask-httpauth) Requirement already satisfied (use –upgrade to upgrade): Jinja2>=2.4 in /root/Envs/RunningFast/lib/python2.7/site-packages (from Flask->flask-httpauth) Requirement already satisfied (use –upgrade to upgrade): Werkzeug>=0.7 in /root/Envs/RunningFast/lib/python2.7/site-packages (from Flask->flask-httpauth) Requirement already satisfied (use –upgrade to upgrade): click>=2.0 in /root/Envs/RunningFast/lib/python2.7/site-packages (from Flask->flask-httpauth) Requirement already satisfied (use –upgrade to upgrade): MarkupSafe in /root/Envs/RunningFast/lib/python2.7/site-packages (from Jinja2>=2.4->Flask->flask-httpauth) Building wheels for collected packages: flask-httpauth Running setup.py bdist_wheel for flask-httpauth … done Stored in directory: /root/.cache/pip/wheels/77/79/bb/9794c29173a793cfba5f5b4cd3c7c576d2445ab6bfb81c8429 Successfully built flask-httpauth Installing collected packages: flask-httpauth Successfully installed flask-httpauth-3.2.1 |
截至目前,此处可以工作的代码是:
/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/server/instance/config.py
#!/usr/bin/python # -*- coding: UTF-8 -*- import os ############################################################ # Flask ############################################################ FLASK_SECRET_KEY = ‘\x8a\x1e\x059\x14xxxxxxx\xcf\xc4’ ############################################################ # SQLAlchemy ############################################################ ## mysql workable: ## mysql://username:password@hostname/database SQLALCHEMY_DATABASE_URI = ‘mysql://uuuuu:ppppp@localhost/runningfast_test’ SQLALCHEMY_TRACK_MODIFICATIONS = False |
/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/server/runningfast/__init__.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask, jsonify
from flask import abort
from flask import make_response
from flask import request
from flask_httpauth import HTTPBasicAuth
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(‘config’) # load config.py
app.config.from_pyfile(‘config.py’)
app.debug = app.config["FLASK_DEBUG"]
fileHandler = RotatingFileHandler(
app.config[‘LOG_FILE_FILENAME’],
maxBytes = 2*1024*1024,
backupCount = 3,
encoding = "UTF-8")
fileHandler.setLevel(logging.DEBUG)
fileLogFormatterStr = app.config["LOG_FILE_FORMAT"]
fileLogFormatter = logging.Formatter(fileLogFormatterStr)
fileHandler.setFormatter(fileLogFormatter)
app.logger.addHandler(fileHandler)
gLog = app.logger
app.secret_key = app.config[‘FLASK_SECRET_KEY’]
auth = HTTPBasicAuth()
tasks = [
{
‘id’: 1,
‘title’: u’Buy groceries’,
‘description’: u’Milk, Cheese, Pizza, Fruit, Tylenol’,
‘done’: False
},
{
‘id’: 2,
‘title’: u’Learn Python’,
‘description’: u’Need to find a good Python tutorial on the web’,
‘done’: False
},
{
‘id’: 3,
‘title’: u’Learn Flask’,
‘description’: u’Need to find a good Flask tutorial on the web’,
‘done’: True
},
{
‘id’: 4,
‘title’: u’test PyCharm upload file’,
‘description’: u’ok or not?’,
‘done’: True
}
]
@app.route(‘/’)
def index():
gLog.debug("got into test root endpoint: /")
return "Hello, Running Fast!"
@app.route(‘/runningfast/api/v1.0/tasks’, methods=[‘GET’])
@auth.login_required
def get_tasks():
return jsonify({‘tasks’: tasks})
@app.route(‘/runningfast/api/v1.0/tasks/<int:task_id>’, methods=[‘GET’])
def get_task(task_id):
task = filter(lambda t: t[‘id’] == task_id, tasks)
if len(task) == 0:
abort(404)
return jsonify({‘task’: task[0]})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({‘error’: ‘Not found’}), 404)
@app.route(‘/runningfast/api/v1.0/tasks’, methods=[‘POST’])
def create_task():
if not request.json or not ‘title’ in request.json:
abort(400)
task = {
‘id’: tasks[-1][‘id’] + 1,
‘title’: request.json[‘title’],
‘description’: request.json.get(‘description’, ""),
‘done’: False
}
tasks.append(task)
return jsonify({‘task’: task}), 201
@app.route(‘/runningfast/api/v1.0/tasks/<int:task_id>’, methods=[‘PUT’])
def update_task(task_id):
task = filter(lambda t: t[‘id’] == task_id, tasks)
if len(task) == 0:
abort(404)
if not request.json:
abort(400)
if ‘title’ in request.json and type(request.json[‘title’]) != unicode:
abort(400)
if ‘description’ in request.json and type(request.json[‘description’]) is not unicode:
abort(400)
if ‘done’ in request.json and type(request.json[‘done’]) is not bool:
abort(400)
task[0][‘title’] = request.json.get(‘title’, task[0][‘title’])
task[0][‘description’] = request.json.get(‘description’, task[0][‘description’])
task[0][‘done’] = request.json.get(‘done’, task[0][‘done’])
return jsonify({‘task’: task[0]})
@app.route(‘/runningfast/api/v1.0/tasks/<int:task_id>’, methods=[‘DELETE’])
def delete_task(task_id):
task = filter(lambda t: t[‘id’] == task_id, tasks)
if len(task) == 0:
abort(404)
tasks.remove(task[0])
return jsonify({‘result’: True})
@auth.get_password
def get_password(username):
if username == ‘miguel’:
return ‘python’
return None
@auth.error_handler
def unauthorized():
return make_response(jsonify({‘error’: ‘Unauthorized access’}), 401)
/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/server/config.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
############################################################
# Flask
############################################################
FLASK_DEBUG = True #启动Flask的Debug模式
FLASK_APP = "RunningFast"
############################################################
# File Log
############################################################
LOG_FILE_FILENAME = "logs/" + FLASK_APP + ".log"
LOG_FILE_FORMAT = "[%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s] %(message)s"
/Users/crifan/dev/dev_root/daryun/Projects/RunningFast/sourcecode/server/run.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from runningfast import app if __name__ == ‘__main__’: #app.run(debug=True) app.run() |
再去: