1

I am using flask blueprint to create dynamic routing. I have followed this Example.

Here is my sample code,

demo = Blueprint('demo', __name__)

@demo.route('/')
def home():
    return  'here'

def add_subdomain_to_global(endpoint, values):
    g.subdomain = values.pop('subdomain', None)

def add_subdomain_to_url_params(endpoint, values):
    if not 'subdomain' in values:
        values['subdomain'] = g.subdomain

def add_subdomain_support(app):
    app.url_value_preprocessor(add_subdomain_to_global)
    app.url_defaults(add_subdomain_to_url_params)

app = Flask(__name__)

app.config['SERVER_NAME']= 'lingam.com'

add_subdomain_support(app)

@app.before_request
def add_user_to_global():
    userdb = {'x':'sorna','y':'lingam'}
    g.user = None
    if g.subdomain:
        g.user = userdb[g.subdomiain]

app.register_blueprint(demo, subdomain='<subdomain>')
if __name__ == "__main__":
    app.run()

when i give ".localhost:5000" i am getting error and when i debugged and found that def add_subdomain_to_global(endpoint, values): in this line {'subdomain':<invalid>}. Wht went wrong and how can i dynamically use subdomain.

Can you please help me.

Error trace

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python34\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python34\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python34\lib\site-packages\flask\app.py", line 1637, in full_dispatch_request
    rv = self.preprocess_request()
  File "C:\Python34\lib\site-packages\flask\app.py", line 1837, in preprocess_request
    rv = func()
  File "E:/Work/Python1/work/So/flasksubdomain.py", line 25, in add_user_to_global
    g.user = userdb[g.subdomain]
 KeyError: '<invalid>'
127.0.0.1 - - [07/Oct/2017 17:09:04] "GET / HTTP/1.1" 500 -
backtrack
  • 7,996
  • 5
  • 52
  • 99
  • `localhost` doesn't support dubdomains. A common workaround is to map an actual domain name to your localhost address. See this answer: https://stackoverflow.com/a/19016600/1925257. But do keep in mind to remove those DNS entries after you're done testing. – xyres Oct 07 '17 at 11:32

0 Answers0