如何使用python-Bottle框架创建REST API应用程序,以及如何在apache服务器上部署restapi应用程序?

2024-03-29 10:58:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

通过使用上述代码,我可以如何创建示例应用程序以及如何在服务器上部署该示例应用程序。如何才能做到这一点?


Tags: run代码name服务器框架apiid应用程序
3条回答

尝试使用“method=GET/POST/PUT/DELETE”

配方-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)

配置.json

{
    "paths" : {
        "xml" : "xml/"
    }
}

@phihag,阅读米格尔·格林伯格的这些文章,@miguelgrinberg~http://blog.miguelgrinberg.com/category/REST

从这篇文章开始,“Designing a RESTful API with Python and Flask”~如果需要安装烧瓶,请完成这些步骤。

然后用瓶子重新写申请表。瓶子是一个简单的框架使用,是如此接近烧瓶,我重新编写的代码阅读通过瓶子的例子。有更多的detailed tutorial你可以看一看,一旦你有了基本知识。

值得努力。

下面您将解释如何使用WSGI在apache中部署bottle应用程序:http://bottlepy.org/docs/dev/deployment.html#apache-mod-wsgi

就应用程序而言,您需要最佳的REST兼容,因此了解REST和bottle,这里有一个很好的教程,我使用了:http://myadventuresincoding.wordpress.com/2011/01/02/creating-a-rest-api-in-python-using-bottle-and-mongodb/

相关问题 更多 >