我想使用python Bottle框架为api创建一个示例应用程序,我想在apache服务器上部署该应用程序,我使用以下示例代码,
from bottle import route, run, template
@route('/hello/:name')
def index(name='World'):
return template('<b>Hello {{name}}</b>!', name=name)
@route('/events/:id', method='GET')
def get_event(id):
return dict(name = 'Event ' + str(id))
run(host='localhost', port=8082)
通过使用上面的代码,我如何创建示例应用程序以及如何在服务器上部署该示例应用程序。怎么能实现这个目标?
答案 0 :(得分:1)
@phihag,请阅读Miguel Grinberg撰写的这些文章,@miguelgrinberg〜http://blog.miguelgrinberg.com/category/REST
从这篇文章开始,“ Designing a RESTful API with Python and Flask ”〜如果需要安装Flask,请完成以下步骤。
然后在Bottle中重写应用程序。 Bottle是一个使用的简单框架,并且非常接近Flask我通过Bottle中的示例重新编写了代码。一旦掌握了基础知识,就可以看到更多detailed tutorial。
值得努力。
答案 1 :(得分:1)
尝试使用&#34;方法= GET / POST / PUT / DELETE&#34;
recipes-api.py
import json
import os
from bottle import route, run, static_file, request
config_file = open( 'config.json' )
config_data = json.load( config_file )
pth_xml = config_data["paths"]["xml"]
@route('/recipes/')
def recipes_list():
paths = []
ls = os.listdir( pth_xml )
for entry in ls:
if ".xml" == os.path.splitext( entry )[1]:
paths.append( entry )
return { "success" : True, "paths" : paths }
@route('/recipes/<name>', method='GET')
def recipe_show( name="" ):
if "" != name:
return static_file( name, pth_xml )
else:
return { "success" : False, "error" : "show called without a filename" }
@route('/recipes/_assets/<name>', method='GET')
def recipe_show( name="" ):
if "" != name:
return static_file( name, pth_xml + "_assets/" )
else:
return { "success" : False, "error" : "show called without a filename" }
@route('/recipes/<name>', method='DELETE' )
def recipe_delete( name="" ):
if "" != name:
try:
os.remove( os.path.join( pth_xml, name + ".xml" ) )
return { "success" : True }
except:
return { "success" : False }
@route('/recipes/<name>', method='PUT')
def recipe_save( name="" ):
xml = request.forms.get( "xml" )
if "" != name and "" != xml:
with open( os.path.join( pth_xml, name + ".xml" ), "w" ) as f:
f.write( xml )
return { "success" : True, "path" : name }
else:
return { "success" : False, "error" : "save called without a filename or content" }
run(host='localhost', port=8080, debug=True)
config.json
{
"paths" : {
"xml" : "xml/"
}
}
答案 2 :(得分:0)
在这里,您将了解如何使用WSGI在apache中部署瓶子应用程序:http://bottlepy.org/docs/dev/deployment.html#apache-mod-wsgi
就应用程序而言,您需要最好的REST兼容,以便了解REST和瓶子,这是我使用的一个很好的教程:http://myadventuresincoding.wordpress.com/2011/01/02/creating-a-rest-api-in-python-using-bottle-and-mongodb/