Python Bottle如何将参数作为json传递

时间:2013-06-11 11:39:28

标签: python json wsgi bottle

我使用瓶子

为openerp创建了一个api

使用浏览器

访问时效果很好

我不知道如何将其作为json参数传递

问题是

如何使用api调用并传递json参数,如

http://localhost/api?name=admin&password=admin&submit=Submit

这是我的wsgi代码app.wsgi

import json
import os
import sys
import bottle
from bottle import get, post, run,request,error,route,template,validate,debug
def login():
        import xmlrpclib
        username = request.forms.get('name')
        pwd = request.forms.get('password')
        dbname = 'more'
        sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
        uid = sock_common.login(dbname, username, pwd)
        if uid:
                return json.dumps({'Success' : 'Login Sucessful'])

def index():
        return '''
        <html>
        <head>
                <title> Portal</title>
        </head>
        <body>Welcome To PORTAL
   <form method="GET" action="/api/links" enctype="multipart/form-data">
   Name:<input name="name" type="text"/><br>
   Password:<input name="password" type="password"/><br>
   <input type="submit" value="Submit" name="submit">
   </form>
   </body>
   </html>'''

def links():
        return '''
        <html>
        <head>
                <title> Portal</title>
        </head>
        <body>
    <a href="/api/advisor">Advisor<br>
   </body>
   </html>'''

application = bottle.default_app()
application.route('/', method="GET", callback=index)
application.route('/', method="POST",callback=login)

2 个答案:

答案 0 :(得分:2)

request.forms用于POST或PUT请求。代码中的表单使用GET而不是POST,因此您应该使用request.query.getall,这样您就可以访问“URL参数”。

答案 1 :(得分:0)

我没有看到代码有什么问题(pep8更改除外),我看到的唯一问题是表单和位置的方法,请参阅下面的固定版本...

import json
import os
import sys
import bottle
from bottle import get, post, run, validate, request, error, route, template, debug


def login():
    import xmlrpclib
    username = request.forms.get('name')
    pwd = request.forms.get('password')
    dbname = 'more'
    sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
    uid = sock_common.login(dbname, username, pwd)
    if uid:
        return json.dumps({'Success': 'Login Sucessful'})


def index():
        return '''
        <html>
        <head>
                <title> Portal</title>
        </head>
        <body>Welcome To PORTAL
   <form method="POST" action="/" enctype="multipart/form-data">
   Name:<input name="name" type="text"/><br>
   Password:<input name="password" type="password"/><br>
   <input type="submit" value="Submit" name="submit">
   </form>
   </body>
   </html>'''


def links():
        return '''
        <html>
        <head>
                <title> Portal</title>
        </head>
        <body>
    <a href="/api/advisor">Advisor<br>
   </body>
   </html>'''


application = bottle.default_app()
application.route('/', method="GET", callback=index)
application.route('/', method="POST", callback=login)

application.run()