前段时间学习使用了falcon框架,针对此框架的学习经验做了如下总结。
1.在学习falcon之前我们先来了解下,该框架的主要作用和运用场景,falcon主要还是针对RESTful服务打造的。
2.接来下我们动手安装一下falcon,python我们用的3.5的版本,使用pip来安装,pip install falcon下载下来,我们还有安装gunicorn,gunicorn主要是后台服务的稳定运行,数据库使用mysql,就需要安装python-mysqldb,安装完就可以开始干活了,falcon的使用感觉很简单的,没有太多的难点,估计是没有使用太多的高级功能吧,反正我们慢慢去发现吧,导入falcon模块,然后就编辑自己的纯逻辑代码,
接下来展示一段代码:
import falcon
class Resource(object):
def on_get(self, req, resp):
resp.body = '{"message":"Hello world!"}'
resp.status = falcon.HTTP_200
api = application = falcon.API()
api.add_route('/test', Resource())
就是这么简单!你已经实现了一个可以响应get请求的类了,同样的post请求只要写成on_post就行了,是不是简单到不敢相信?先将上面的代码保存为test.py,接下来,继续编写代码,然后试着运行,就能让你的服务器真正的跑起来了。再写个app.py,内容如下:
import falcon
import test
api = application = falcon.API()
test = test.Test()
# 添加路由控制
api.add_route('/test', test)
打开终端到当前目录下运行以下命令:gunicorn [-b 127.0.0.1:8000] app
现在你可以去浏览器打开127.0.0.1:8000/test了,会出现{"message": "Hello world"},你的服务器已经跑起来了,是不是感觉很棒!这差不多就是用falcon开发API所要做的所有事情了(至少我目前为止只用到了这些, -b参数可以绑定ip和端口号,默认就是127.0.0.1:8000)。
接下来的这段代码是使用mysqldb连操作数据库的,依旧很简单:
import MySQLdb
class DBTest(object):
def test(self):
try:
conn = MySQLdb.connect(host='host',user='user',passwd='psw',port=3306)
cur = conn.cursor()
cur.execute('create database if not exists test default character set utf8 default collate utf8_general_ci')
conn.select_db('test')
cur.execute('create table test(id int, title varchar(20))')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error, e:
print "Error >>> " + str(e)
好了到目前为止我们就学习到这儿了。