【问题标题】:How I can pass environment variables to my flask application如何将环境变量传递给我的烧瓶应用程序
【发布时间】:2018-11-08 22:10:29
【问题描述】:

我是 Python 新手,正在编写一个简单的烧瓶 api,它将连接到 azure cosmos DB 并返回一些响应。

我想将 db 连接字符串作为环境变量传递,因为我需要 dockerize 这个应用程序。

所以我不确定如何将此连接字符串作为环境变量传递给我的 Flask 应用程序,以及如何从命令窗口运行和测试我的 Flask 应用程序。

下面是我的一段代码。

import os
from flask import Flask, request, render_template
from azure.storage.table import TableService, Entity

APP = Flask(__name__)
APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
connectionstring = os.environ['connectionstring']

@APP.route('/getdata')
def view_registered_guests():
print("Inside method");

table_service = TableService(connection_string=connectionstring)
table_name = 'tablebasics'
entity = table_service.get_entity(table_name, 'Harp', '2')
print(entity['email'])
print(entity['phone'])
return "Email: "+entity['email'] +" phone no: "+ entity['phone'];

if __name__ == '__main__':
APP.run(debug=True)

任何帮助将不胜感激。

谢谢,

【问题讨论】:

  • 我猜这就是你要找的东西:flask.pocoo.org/snippets/2
  • @Abhinay 不,OP 正在谈论 环境 变量。
  • 我不想使用配置文件。我需要将此连接字符串作为环境变量传递。

标签: python flask environment-variables


【解决方案1】:

使用os 模块

os.environ["connectionstring"]

您可以在windows cmd中使用SET设置环境变量

set connectionstring=SOMETHING

【讨论】:

  • 那已经存在了.. connectionstring = os.environ['connectionstring'].
  • 用户已经在使用环境变量。请检查上面的代码。
  • 我不确定我的代码是否正确。如果是,那么有人可以告诉我如何从 cmd 运行它并传递这个 env 变量,或者是否有其他方式来运行和测试它
【解决方案2】:

为了测试这一点,我只是在系统环境变量(系统变量)中添加了“connectionstring”变量及其值,然后运行了我的 py 文件,它就可以工作了。

感谢大家的提示。

【讨论】:

    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2016-07-31
    • 1970-01-01
    • 2019-06-18
    • 2018-07-13
    • 2021-07-20
    相关资源
    最近更新 更多