<Flask>url_for

2017/11/14

url_forを少し試す。

In [70]: from flask import Flask, url_for

In [71]: app = Flask(__name__)

url確認。

In [72]: app.url_map
Out[72]: Map([<Rule /static/<filename> (GET, HEAD, OPTIONS) -> static>])

ルーティング。

In [74]: @app.route(/hage1/)
    ...: def hage1():
    ...:     pass
    ...: 

In [75]: app.url_map
Out[75]: 
Map([<Rule /hage1/ (GET, HEAD, OPTIONS) -> hage1>,
 <Rule /static/<filename> (GET, HEAD, OPTIONS) -> static>])

In [76]: @app.route(/hage2/)
    ...: def hage2():
    ...:     pass
    ...: 

In [77]: app.url_map
Out[77]: 
Map([<Rule /hage1/ (GET, HEAD, OPTIONS) -> hage1>,
 <Rule /hage2/ (GET, HEAD, OPTIONS) -> hage2>,
 <Rule /static/<filename> (GET, HEAD, OPTIONS) -> static>])

で、url_for()してみる。

In [78]: with app.app_context():
    ...:     print(url_for(hage1))
    ...:     
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-78-fdee3e496b8a> in <module>()
      1 with app.app_context():
----> 2     print(url_for(hage1))
      3 

C:Anaconda3Libsite-packagesflaskhelpers.py in url_for(endpoint, **values)
    285         url_adapter = appctx.url_adapter
    286         if url_adapter is None:
--> 287             raise RuntimeError(Application was not able to create a URL 
    288                                adapter for request independent URL generation. 
    289                                You might be able to fix this by setting 

RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.

ゲロっちー。
文句に従い、SERVER_NAMEを設定。

In [79]: app.config[SERVER_NAME] = /saba/

In [81]: with app.app_context():
    ...:     print(url_for(hage1))
    ...:     
http:///saba//hage1/

なるほど。

マニュアル

http://flask.pocoo.org/docs/0.10/api/#flask.url_for

http://flask.pocoo.org/docs/0.10/appcontext/#creating-an-application-context