How to get base url of website in jinja2?

2019-07-05 12:56发布

PHP has $_SERVER['DOCUMENT_ROOT'] as a reference to the base url of a website: e.g. http://localhost:8080/. I need to do the same in jinja2. I am using python 2.7 on app engine.

How do I get the base url of website in jinja2?

2条回答
贪生不怕死
2楼-- · 2019-07-05 13:11

webapp2 is based on WebOb. From their docs

WebOb is a Python library that provides wrappers around the WSGI request environment, and an object to help create WSGI responses. The objects map much of the specified behavior of HTTP, including header parsing, content negotiation and correct handling of conditional and range requests.

Accessing the application URL is enabled by the request object in a handler and can be accessed via the attribute application_url:

import webapp2
class MainHandler(webapp2.RequestHandler):
  def get(self):
    self.response.write(self.request.application_url)
查看更多
Melony?
3楼-- · 2019-07-05 13:35

In webapp2, you can get the host part of a request and pass it as argument in a jinja template as follows:

class YourHandler(webapp2.RequestHandler):
  def get(self):
    params = {'url':self.request.host}
    template = jinja_environment.get_template('your_template.html')
    self.response.write(template.render(params))
查看更多
登录 后发表回答