Python搭建HTTP服务器:API接口(支持RESTful API)

API接口包含:

  • GET API
  • POST API
  • RESTful API
  • 文件上传API

# coding=utf-8

import os
from flask import Flask, jsonify, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = 'D:/www/upload'
ALLOWED_EXTENSIONS = set(['txt', 'apk', 'zip', 'rar'])

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Hello World
@app.route('/')
def hello_world():
    return 'Hello World!'

# RESTful API
@app.route("/user/<int:id>")
def user(id):
    return jsonify(id=id, username='Joe.Ye', head_url='http://www.androidios.cc/images/avatar.png')

# GET API
@app.route("/user/info")
def user_info():
    id = request.args.get("id")
    print request.headers
    return jsonify(id=id, username='Joe.Ye', head_url='http://www.androidios.cc/images/avatar.png')

# POST API
@app.route("/login", methods=["POST"])
def login():
    username = request.form.get("username");
    password = request.form.get("password");

    if username=='AppBlog.CN' and password=='123456':
        return jsonify(code=1, message=u'登录成功')

    return jsonify(code=0, message=u'用户名或者密码错误')

# POST API(JSON)
@app.route("/login/json", methods=["POST"])
def login_json():
    json = request.get_json();
    username = json.get("username");
    password = json.get("password");

    if username=='AppBlog.CN' and password=='123456':
        return jsonify(code=1, message=u'登录成功')

    return jsonify(code=0, message=u'用户名或者密码错误')

# POST API
@app.route("/user/new", methods=["POST"])
def user_create():
    json = request.get_json()
    print json

    id = json.get("id")
    username = json.get("username");
    print id
    print username

    return jsonify(code=1, message=u"保存用户成功")

# POST API
@app.route("/user/edit", methods=["POST"])
def user_edit():
    id = request.form.get("id")
    username = request.form.get("username")

    print request.headers

    return jsonify(code=1, message=u"更新用户用户成功")

# 校验文件类型
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 文件上传API,请查看文章底部附言
@app.route("/upload", methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        username = request.form.get("username")
        print 'username = ' + username
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print 'file = ' + filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #return redirect(url_for('upload'))
            return jsonify(code=1, message=u'文件上传成功')
    return """
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method="post" enctype="multipart/form-data">
        <input type=file name=file>
        <input type=submit value=Upload>
    </form>
    <p>%s</p>
    """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == '__main__':
    app.run(host='0.0.0.0')
上一篇 Python搭建HTTP服务器:PyCharm安装Flask等库
下一篇 Python import错误处理
目录
文章列表
1 Gitlab大版本升级思路
Gitlab大版本升级思路
2
Redis 服务器命令
Redis 服务器命令
3
腾讯企业邮箱配置图文教程
腾讯企业邮箱配置图文教程
4
RadioButton在Android 4.4及以下调用setButtonDrawable(null)无效的问题
RadioButton在Android 4.4及以下调用setButtonDrawable(null)无效的问题
5
Zuul使用Filter修改请求参数、请求头和响应头
Zuul使用Filter修改请求参数、请求头和响应头
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。