2017-08-19 43 views
1

我使用python 2.7 + Flask運行GAE應用程序,並使用SENDGRID第三方庫發送電子郵件。如何將字符串導入到app.yaml?

而且,我想將此項目上傳到Github,所以我需要在app.yaml中隱藏我的SENDGRID_API_KEY。 app.yaml中的

部分看起來像這樣

env_variables: 
    SENDGRID_API_KEY: 'my_send_grid_api_key' 

我已經存儲的所有敏感鍵config.py。所以我想將'my_send_grid_api_key'部分替換爲cofing.Sendgrid_API_Key或類似的東西。

如何將字符串導入到app.yaml或指向config.py?

回答

0

可以使用yaml模塊到app.yaml數據加載到一個字典和更新:

from config import Sendgrid_API_Key 
import yaml 

with open('app.yaml') as f: 
    app_data = yaml.load(f) 

app_data['env_variables']['SENDGRID_API_KEY'] = Sendgrid_API_Key 

with open('app.yaml', 'w') as f: 
    yaml.dump(app_data, f) 
+0

該解決方案似乎是非常有前途的,我會稍後再試回來非常感謝你。 –

0

你爲什麼想要保存SendGrid API密鑰作爲環境變量?

在你的代碼,使調用SendGrid你可以這樣做:

from config import Sendgrid_API_Key 
SG = sendgrid.SendGridAPIClient(apikey= Sendgrid_API_Key) 
SG.client.mail.send.post(request_body=data) 
+0

[SendGrid官方指南](https://github.com/sendgrid/sendgrid-python)表示將SendGrid API密鑰設置爲環境變量。我做了你之前做過的事情,並且遇到HTTP 401錯誤,並且在我簡單地將API密鑰更改爲環境變量後,問題解決了。 –

+0

這就是我這樣做的方式,所以它可以這樣工作。在您的設置中必須有其他內容導致401錯誤。 –

+0

我不認爲SendGrid會知道如何設置API密鑰,因爲它在您的服務器中完成。 – marcadian

相關問題