webpy: How to serve JSON

前端 未结 2 1317
执笔经年
执笔经年 2020-12-13 10:26

Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages.

I try to lo

相关标签:
2条回答
  • 2020-12-13 10:38

    I wouldn't think you'd have to do any thing overly "special" for web.py to serve JSON.

    import web
    import json
    
    class index:
        def GET(self):
            pyDict = {'one':1,'two':2}
            web.header('Content-Type', 'application/json')
            return json.dumps(pyDict)
    
    0 讨论(0)
  • 2020-12-13 10:42

    It is certainly possible to serve JSON from webpy, But if you and choosing a framework, I would look at starlight and my fork twilight (for documentation).

    It has a JSON wrapper for fixing the http headers for your json response.

    it uses either the json or simplejson libraries for json handling the conversions to and from other objects.

    I am using it right now and it is great.

    https://bitbucket.org/marchon/twilight

    in it you will find an example called ShowMeTheJson.py

    that uses simple json

    from starlight import *
    from werkzeug.routing import Map
    from werkzeug.routing import RuleFactory
    
    import simplejson
    
    
    class ShowMeTheResponses(App):
    
    ####################################################################
    #
    #   Sample URLS to Test Responses 
    #
    #   http://localhost:8080/                root
    #
    #   http://localhost:8080/json            return JSON Mime Type Doc  
    #
    ###################################################################
    
    
    
       @default
       def hello(self):
           return 'Hello, world!'
    
       @dispatch('/')
       def index(self): 
           return 'Hello Root!'
    
       @dispatch('/html')
       def indexhtml(self): 
           return HTML('Hello HTML')
    
       @dispatch('/json')
       def indexjson(self):
           directions = {'N' : 'North', 'S' : 'South', 'E':'East', 'W' : 'West'}
           return JSON(simplejson.dumps(directions))         
    
    
    if __name__ == '__main__':
        from werkzeug import run_simple
        run_simple('localhost', 8080, ShowMeTheResponses())
    
    0 讨论(0)
提交回复
热议问题