Flask shell - 如何为url_for设置服务器名称_external = True?

时间:2016-06-04 15:23:57

标签: flask jinja2

我有一个在docker容器中运行的烧瓶应用程序。一切正常,除非我想在烧瓶外壳的同一个docker容器中做一些手工作业。问题是url_for(x, _external=True)始终返回https://localhost,并不重要我尝试在shell中设置服务器名称。 我显然已尝试将SERVER_NAME设置为无变化。

$ python manage.py shell
>>> from flask import current_app
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> from app import models
>>> models.Registration.send_registration(id=123)

jinja模板具有: {{ url_for('main.index', _external=True, _scheme='https') }}

哪个生成: https://localhost

我想得到: https://example.com

我正在使用Flask 0.11,Werkzeug 0.11.10和Jinja2 2.8

2 个答案:

答案 0 :(得分:5)

您的应用使用创建应用程序上下文时定义的SERVER_NAME

如果要在shell中执行此操作,可以在设置SERVER_NAME后创建测试请求上下文。

>>> from flask import current_app, url_for
>>> current_app.config['SERVER_NAME'] = 'example.com'
>>> with current_app.test_request_context():
...     url = url_for('index', _external=True)
...
>>> print url
http://example.com/

我们可以挖掘Flask代码来理解它。

Flask url_for使用appctx.url_adapter来构建此网址。初始化AppContext时会定义此url_adapter,并且在启动shell时会发生此SERVER_NAME。它调用app.create_url_adapter并使用定义的Sub FillGoldenData() Dim GoldenSht, Backendsht As Worksheet Dim Glr, Blr As Integer Dim goldenrs As ADODB.Recordset Dim GoldenQry As String dim dbconn dbconn As ADODB.Connection Set GoldenSht = ThisWorkbook.Sheets("Golden") Set Backendsht = ThisWorkbook.Sheets("Backend") Set dbconn = New ADODB.Connection Set GoldenRs = New ADODB.Recordset GoldenQry = "" For p = 2 To 189 GoldenQry = GoldenQry & Backendsht.Range("F" & p).Value & vbNewLine Next p Set dbconn = New ADODB.Connection Server = "brd.prod.human" UserId = "CHANDRESHBATRA" Password1 = "Welcome12" With dbconn .CommandTimeout = 30 .Open "PROVIDER=MSDASQL;" & _ "DRIVER={Microsoft ODBC for Oracle};" & _ "SERVER=" & Server & ";" & _ "UID=" & UserId & ";PWD=" & Password1 & ";" End With goldenrs.Open GoldenQry, dbconn, adOpenDynamic If Not (goldenrs.EOF) Then With GoldenSht.Range("A2") .CopyFromRecordset goldenrs End With End If Else MsgBox "There is no Isin" Exit Sub End If End Sub

答案 1 :(得分:2)

此解决方案与已经介绍的解决方案非常相似,但所需步骤更少:

from flask import current_app, url_for

with current_app.test_request_context('localhost.com'):
    url = url_for('index')
    ...

这样,由于我们在现场注入了SERVER_NAME,因此reqctx可以正确地构建路径,因此无需设置配置url_for。就我而言,我想要一个相对路径,因此不需要添加属性_external