How should an index.html file be served from Python Pyramid for an AngularJS app?

99封情书 提交于 2019-12-11 06:38:49

问题


I am getting into single-page apps with AngularJS but rather than using Node or similar, I am most comfortable with Python on the server. So, given I am somewhat familiar with Pyramid, I plan to use the pyramid_rpc module to return JSON objects to the client app. That's all straight forward enough, however, what then is the best way to serve the starting index file which contains the AngularJS initial AngularJS app? Usually, static files are served from a static directory, but is there any problem serving a index.html file from the root? Or should I use a view-callable and '/' route with a renderer to a html template? All that being said, is Pyramid overkill for this kind of application? Any advice would be great.


回答1:


If you're planning to return some JSON responses then Pyramid is a great option. But I wouldn't recommend using pyramid_rpc. JSON-RPC is a protocol that is intended for RPC communication between servers. Straight json responses fit most clients (like browsers) better such as just a bunch of routes that return JSON responses in response to GET/POST requests. This is also a good place to serve up index.html, probably with a good http_cache parameter to prevent clients from requesting that page too often (of course you can go further with optimizing this route, but you should probably save that for later).

config.add_route('index', '/')
config.add_route('api.users', '/api/users')
config.add_route('api.user_by_id', '/api/users/{userid}')

@view_config(route_name='index', renderer='myapp:templates/index.html', http_cache=3600*24*365)
def index_view(request):
    return {}

@view_config(route_name='api.users', request_method='POST', renderer='json')
def create_user_view(request):
    # create a user via the request.POST parameters
    return {
        'userid': user.id,
    }

@view_config(route_name='api', request_method='GET', renderer='json')
def user_info_view(request):
    userid = request.matchdict['userid']
    # lookup user
    return {
        'name': user.name,
    }


来源:https://stackoverflow.com/questions/17246706/how-should-an-index-html-file-be-served-from-python-pyramid-for-an-angularjs-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!