用python 和 flask 建立Web API 的简单入门

本文通过学习 https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask 而来,例子和数据库例子也是来自该文。

本文先介绍api的使用,然后通过几个例子一步步解说rest api 的设计。例子包括:第一个基本例子,有返回的例子,带参数查询的例子,数据库查询的例子。理解这几个例子,你就入门了。

理解api

下面是使用api的例子:

http://chroniclingamerica.loc.gov/search/pages/results/?format=json&proxtext=fire

这个返回一个json 数据集。

这里包括以下三个部分。

基本的url 部分是

http://chroniclingamerica.loc.gov

 路径是:

/search/pages/results/

参数部分是:

?format=json&proxtext=fire

 

准备

安装好python 3 和 flask

pip install flask

建立一个目录projects,然后在这个目录下建立一个api的目录。

第一个例子

在这个目录下建立一个api.py 的python文件,内容如下:

import flask

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/', methods=['GET'])
def home():
    return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"

app.run()

在命令行下执行python api.py

可以看到类似下面的提示内容:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

按照这个提示在浏览器里输入 http://127.0.0.1:5000/ 就可以看到网页:

这是显示的第一个界面。

有数据返回的例子

下面添加一点内容,增加返回一个数据表这个api。更改这个文件的代码如下:

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True

# Create some test data for our catalog in the form of a list of dictionaries.
books = [
    {'id': 0,
     'title': 'A Fire Upon the Deep',
     'author': 'Vernor Vinge',
     'first_sentence': 'The coldsleep itself was dreamless.',
     'year_published': '1992'},
    {'id': 1,
     'title': 'The Ones Who Walk Away From Omelas',
     'author': 'Ursula K. Le Guin',
     'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
     'published': '1973'},
    {'id': 2,
     'title': 'Dhalgren',
     'author': 'Samuel R. Delany',
     'first_sentence': 'to wound the autumnal city.',
     'published': '1975'}
]


@app.rou
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值