I have an application that uses some environments variables like host, users, dbname to protect sensive data in a database connection. In local ambient, using localhost with Pycharm IDE that works fine!!! But when I upload code to Heroku, it don´t recognize my environment variables and app crashes.
Here is small code showing how I call variables at Pycharm IDE. That is fine for localhost:
from flask.app import Flask
from flask.templating import render_template
from flask_socketio import SocketIO, emit, send
import os
app = Flask(__name__)
host = os.environ['HOST']
dbname = os.environ['dbname']
#app.route("/")
def home():
return('<div>Host: ' + host + '</div><div>Dbname: ' + dbname + '</div>'
)
if __name__ == "__main__":
#io.run(app, debug=False)
app.run()
Here is response in local browser, that´s ok!
enter image description here
In Heroko, config var are equal variables above, follow print os settings:
Here is the result of same code uploaded to Heroku
enter image description here
And here is the return of logs --tail from heroku
enter image description here
enter image description here
Well, any suggestions to solve this problem? How can I adapt code to run in Heroku app?
Thx
Related
I tried to find a solution for my problem in other questions but I couldn't.
I downloaded the python flask and made my first flask app and it ran fine.
Here is the code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
When I ran my second file where I had added an app.route ("/ david") and followed the same procedure again, refreshed it and nothing changed.
That is to say, I was going to / david and I get an URL error
Here is my second file
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
#app.route("/david")
def david():
return "Hello, David!"
I tried the same with other files which have some added routes and the result is the same as the first file
Thanks for your answers, I hope to solve my problem.
You did not run the app. What you did is just create a structure for flask, but did not start the server.
Just add:
app.run()
To the bottom of the file and it will work. It will with start the flask server at http://localhost:5000.
By default, flask runs on port 5000.
It can be changed by:
app.run(host="0.0.0.0", port=xxxx)
0.0.0.0 means it accepts request from anywhere on the port specified.
Make sure you have all the permissions and nothing else is running if you want it to run on port 80.
Hope this helps. Good luck.
I had the same issue. Try first by restarting your IDE; this worked for me. If that doesn't work, try clearing your ports for Windows:
Open Task manager
Click on the “Processe” tab
Enable the "PID" column: View -> Select Columns -> Check the box for PID
Find the PID (in your case, 5000 - flask default port) and click “END PROCESS"
I am following the docker tutorials from the docker website (https://docs.docker.com/get-started/part2/) and trying to run an app (app.py - code given below) after building the image "friendlyhello". However when I try to run the app, I get the below error. I guess it is something to do with the code (app.py)
I have built the docker image successfully. However when I try to run the app which is to display the output in the browser, I get an error as
Name error: name "null" is not defined as shown in the screenshot below
I believe this because of the json format of the app.py which has a parameter execution_count and value as null. I understand pYthon has "None" but when I manually change it run, it still throws the same error
App.py - from the tutorial website
from flask import Flask
from redis import Redis, RedisError
import os
import socket
# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2,
socket_timeout=2)
app = Flask(__name__)
#app.route("/")
def hello():
try:
visits = redis.incr("counter")
except RedisError:
v isits = "<i>cannot connect to Redis, counter disabled</i>"
html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>" \
"<b>Visits:</b> {visits}"
return html.format(name=os.getenv("NAME", "world"),
hostname=socket.gethostname(), visits=visits)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
JSON format - autogenerated - I only have Jupyter notebook and don't have pycharm in my system to open it. Not sure whether how is this json format generated.
I expect the output to be able to run the docker image and see the output as shown in the image below
Output
I am new to Python and writing a simple flask api which will connect to azure cosmos DB and return some response.
I want to pass db connection string as environment variable as going forward I need to dockerize this application.
So I am not sure how I can pass this connection string to my Flask application as environment variable and how to run and test my Flask application from command windows.
Below is my piece of code.
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)
Any help will be appreciated.
Thanks,
Use os module
os.environ["connectionstring"]
You can set environment variables in windows cmd using SET
set connectionstring=SOMETHING
To test this i just added "connectionstring" variable and its value in system environment variables (System variables) and ran my py file and it worked.
Thanks everyone for you hints.
I've been trying to deploy my kik api to heroku, but it just isn't working. I've set up my procfile, my requirements.txt file, my runtime.txt file, and it shows up on my machine as running fine. However, when I open the kik app on my phone and try to message the bot, the messages aren't sent and it is not echoing my message. By Using ngrok as a webhook, I was able to get the bot to work and echo the messages just fine. However, when I tried deploying to heroku, it didn't work at all. For reference, the kik bot is written using flask and the kik api, here is my code
from flask import Flask, request, Response
import os
from kik import KikApi, Configuration
from kik.messages import messages_from_json, TextMessage
app = Flask(__name__)
BOT_USERNAME = os.environ['BOT_USERNAME']
BOT_API_KEY= os.environ['BOT_API_KEY']
kik = KikApi(BOT_USERNAME, BOT_API_KEY)
config = Configuration(webhook=os.environ['WEBHOOK'])
kik.set_configuration(config)
#app.route('/', methods=['POST'])
def incoming():
if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
return Response(status=403)
messages = messages_from_json(request.json['messages'])
for message in messages:
if isinstance(message, TextMessage):
kik.send_messages([
TextMessage(
to=message.from_user,
chat_id=message.chat_id,
body=message.body
)
])
return Response(status=200)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
print('HI')
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Here is my requirements.txt
Flask==0.11.1
kik==1.1.0
gunicorn==19.6.0
Here is my runtime.txt
python-2.7.12
Here is my procfile
web: python bot.py
I set up the webhook variable to be the heroku URL. When I run the app locally, it seems to be running just fine.
Heroku local app
Any help is greatly appreciated.
I figured out the issue. I had set the wrong environmental variables for my heroku deployment, so it threw a keyerror because it couldn't find the key and stopped the process.
I have an ubuntu server running Apache and am trying to connect to an sql server on the same network.
When I run python in terminal and import pymssqlandthen connect, there are no problems connecting but when I put the same code in the init.py it stops running at the conn=pymssql.connect line. Any body have a clue on this?
__init__.py
from flask import Flask, url_for, render_template
import pymssql
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, I love Digital Ocean!"
#app.route("/Reports")
def test():
conn=pymssql.connect(server='<fillinServer>', user='<fillinuser>', password='<fillinpassword>', database='<fillindatabase>')
print "1"
cursor=conn.cursor()
cursor.execute("SELECT TOP 1 * FROM testquery;")
print "2"
row=cursor.fetchone()
print "3"
t= row[1]
return render_template("test.html", test=t)
if __name__ == "__main__":
app.run(debug=True)
.WSGI
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/Reports/")
from ReportApp import app as application
application.secret_key = 'Add your secret key'
Try running your code directly from flask.
Change:
if __name__ == "__main__":
app.run(
host="0.0.0.0", #replace this with your ip
port=int("80"), #replace with your port
debug=True)
Make sure all packages and modules are correctly installed in root/virtual environment.
sudo python app.py
If you have tabs and 4 white spaces mixed it will alert you. Clean/debug your script and re-run it.
After fixing these if the script is running in web-browser, it is probably executing your command. My script took a while since I was connecting to a busy BI server.
p.s. add:
print("done")
so you know script has executed properly.
I can tell you that it worked for me.