flask service on heroku - python

I'm trying to figure out how to run a web service on heroku using flask and JSONRPC.
I would like to get to a point where, from my desktop I can do:
from flask_jsonrpc.proxy import ServiceProxy
service = ServiceProxy('http://<myapp>.heroku.com/api')
result = service.App.index()
print result
looking at heroku logs I can see :
2014-07-05T13:18:42.910030+00:00 app[web.1]: 2014-07-05 13:18:42 [2] [INFO] Listening at: http://0.0.0.0:21040 (2)
and trying using that port with :
service = ServiceProxy('http://<myapp>.heroku.com:21020/api')
still doesn't make it work (it seems hanging)
But when I run this through foreman, though, I can happy access it and seems working fine.
but when I try with the deployed application I get:
ValueError: No JSON object could be decoded
This is the application (not much I know , but is just to see how heroku works)
import os
from flask import Flask
from flask_jsonrpc import JSONRPC
app = Flask(__name__)
jsonrpc = JSONRPC(app, '/api', enable_web_browsable_api=True)
#jsonrpc.method('App.index')
def index():
return u'Welcome to Flask JSON-RPC'
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', debug=True, port=port)
this is the content of my Procfile:
web: gunicorn run:app -p $PORT
Am I missing something obvious here ?
Cheers.
L.
p.S
accessing http://.heroku.com/api/browse
from within the through foreman and the deployed app, it seems working fine.
[edit]
solved :
yes I was missing something.... looking better a the log I noticed the host which was :
host=<myapp>.herokuapp.com
instead of
.heroku.com
Changing the address to the correct one, it all seems working fine.
http://.herokuapp.com/api

All sorted , see original post.
Sorry for the noise.

Related

Python Flask app route is not working well

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"

Docker - Can't get user webcam: getUserMedia() no longer works on insecure origins

WHAT WORKS
I created a simple Web Application in Flask that takes care of operating a simple return render_template("index.html") when the root node is accessed by a Web Browser.
# app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80)
The index.html is a simple page that uses tracking.js in order to get the user webcam and track his/her face in the live video stream.
Opening cmd and typing python app.py results in Running on http://127.0.0.1:80/
Accessing the above mentioned URL results in the correct display of the page, that asks me for permission to use the camera, opens it and correctly tracks my face in the live video feed. So it's all working fine till here.
WHAT DOES NOT WORKS
The problem I'm experiencing arises when I dockerize my application using Docker. docker-machine ip is 192.168.99.100
Opening cmd and typing: docker run -p 4000:80 my_face_track_app results in: Running on http://0.0.0.0:80/
Accessing 192.168.99.100:4000 results in the correct display of index.html but I am not asked anymore for permission on the camera and inspecting the JS console I read the following exception:
getUserMedia() no longer works on insecure origins
Here the full error log:
I know the error is telling me I'm not serving the page in HTTPS.
Has anyone else encountered this problem?
What would be the proper solution to the issue or a possible walkaround?
Any help will be highly appreciated, thank you a lot in advance
WHAT I HAVE TRIED TO DO IN ORDER TO SOLVE THE PROBLEM
Since an HTTPS serving of the page is needed in order for JS to execute the function getUserMedia() I tought about serving my Flask application with an SSL certificate by modifying app.py like this:
# app.py
from flask import Flask, render_template
import OpenSSL
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80, ssl_context="adhoc")
I then dockerized the app building a new image. Typing:
docker run -p 443:80 facetrackapphttps
Results in
Running on https://127.0.0.1:80
So yeah, here HTTPS is ON: the problem is that the port 80 of the HTTPS Flask App is mapped to the port 443 of the docker-machine ip 192.168.99.100.
Trying to access 192.168.99.100:443 does not work and nothing is shown.
Does anybody have an idea about how to do this?
If your application is bound to 127.0.0.1 inside the container, you're not going to be able to access it from your host. According to the flask docs, flask will bind to 127.0.0.1 by default.
You'll need to modify your service so that it binds to 0.0.0.0 inside the container:
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, ssl_context="adhoc")

deploying kik bot to heroku not working

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.

flask 'hello world' not working

I copy pasted the flask's 'hello world' app from their website and am trying to run it. I get an error message in Chrome saying
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Here is the 'hello world' app straight from flasks website
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.debug = True
app.run()
What I have tried:
-temporarily disabling Avast!
-disabling windows firewall
-ensuring that the flask module is installed
This was working a couple days ago actually...
I don't know why but when I change
app.run()
to
app.run(port=4996)
it starts working. No idea why the default port is throwing an error. Oh well.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__name__':
app.run()
app.run(port=5000)
For Windows machines you can use the command in cmd:
set FLASK_APP=python_file.py
flask run
Some other process is running on port 5000. It may be you still have an old Flask process running, with broken code. Or a different web server altogether is running on that port. Shut down that process, or run on a different port.
You can switch to using a different port with the port argument to app.run():
app.run(port=8080)
If you can't figure out what process is still bound to port 5000, use the Windows Resource Monitor or run netstat -a -b from a command line. See How can you find out which process is listening on a port on Windows?
I think you are trying to copy the route generated through your flask program in cmd by pressing ctrl+c which quits your running flask program . i was also doing the same.just try to type the route generated by your flask program on your browser . it will definitely resolve your problem.
Where your python file store is, use cmd and then go on your file store directory, then
set FLASK_APP=filename.py
After this your flask run cmd will work.
from flask import Flask
app = Flask(__name__) # creating app
#app.route('/', methods['GET']) #routing it to the home page
def home(): #function
return "hello world"
app.run(port=5000, debug=true) #function call by the app
Add port and use methods whatever your need is USE GET in your case and try to remove your cache and run the this code it will definitely work.

Debugging a Flask app running in Gunicorn

I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my logs.
I've tried many different configs/options.. I guess I must be missing something obvious.
My gunicorn.conf:
import os
bind = '127.0.0.1:8002'
workers = 3
backlog = 2048
worker_class = "sync"
debug = True
proc_name = 'gunicorn.proc'
pidfile = '/tmp/gunicorn.pid'
logfile = '/var/log/gunicorn/debug.log'
loglevel = 'debug'
An example of some Flask code that borks- testserver.py:
from flask import Flask
from flask import render_template_string
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
#app.route('/')
def index():
n = 1/0
return "DIV/0 worked!"
And finally, the command to run the flask app in gunicorn:
gunicorn -c gunicorn.conf.py testserver:app
Thanks y'all
The accepted solution doesn't work for me.
Gunicorn is a pre-forking environment and apparently the Flask debugger doesn't work in a forking environment.
Attention
Even though the interactive debugger does not work in
forking environments (which makes it nearly impossible to use on
production servers) [...]
Even if you set app.debug = True, you will still only get an empty page with the message Internal Server Error if you run with gunicorn testserver:app. The best you can do with gunicorn is to run it with gunicorn --debug testserver:app. That gives you the trace in addition to the Internal Server Error message. However, this is just the same text trace that you see in the terminal and not the Flask debugger.
Adding the if __name__ ... section to the testserver.py and running python testserver.py to start the server in development gets you the Flask debugger. In other words, don't use gunicorn in development if you want the Flask debugger.
app = Flask(__name__)
app.config['DEBUG'] = True
if __name__ == '__main__':
app.run()
## Tip for Heroku users:
Personally I still like to use `foreman start`, instead of `python testserver.py` since [it sets up all the env variables for me](https://devcenter.heroku.com/articles/config-vars#using-foreman). To get this to work:
Contents of Procfile
web: bin/web
Contents of bin/web, file is relative to project root
#!/bin/sh
if [ "$FLASK_ENV" == "development" ]; then
python app.py
else
gunicorn app:app -w 3
fi
In development, create a .env file relative to project root with the following contents (docs here)
FLASK_ENV=development
DEBUG=True
Also, don't forget to change the app.config['DEBUG']... line in testserver.py to something that won't run Flask in debug mode in production.
app.config['DEBUG'] = os.environ.get('DEBUG', False)
The Flask config is entirely separate from gunicorn's. Following the Flask documentation on config files, a good solution would be change my source to this:
app = Flask(__name__)
app.config.from_pyfile('config.py')
And in config.py:
DEBUG = True
For Heroku users, there is a simpler solution than creating a bin/web script like suggested by Nick.
Instead of foreman start, just use foreman run python app.py if you want to debug your application in development.
I had similiar problem when running flask under gunicorn I didn't see stacktraces in browser (had to look at logs every time). Setting DEBUG, FLASK_DEBUG, or anything mentioned on this page didn't work. Finally I did this:
app = Flask(__name__)
app.config.from_object(settings_map[environment])
if environment == 'development':
from werkzeug.debug import DebuggedApplication
app_runtime = DebuggedApplication(app, evalex=False)
else:
app_runtime = app
Note evalex is disabled because interactive debbugging won't work with forking (gunicorn).
I used this:
gunicorn "swagger_server.__main__:app" -w 4 -b 0.0.0.0:8080
You cannot really run it with gunicorn and for example use the flask reload option upon code changes.
I've used following snippets in my api launchpoint:
app = Flask(__name__)
try:
if os.environ["yourapp_environment"] == "local":
run_as_local = True
# some other local configs e.g. paths
app.logger.info('Running server in local development mode!')
except KeyError as err:
if "yourapp_environment" in err.args:
run_as_local = False
# some other production configs e.g. paths
app.logger.info('No "yourapp_environment env" given so app running server in production mode!')
else:
raise
...
...
...
if __name__ == '__main__':
if run_as_local:
app.run(host='127.0.0.1', port='8058', debug=True)
else:
app.run(host='0.0.0.0')
For above solution you need to give export yourapp_environment = "local" in the console.
now I can run my local as python api.py and prod gunicorn --bind 0.0.0.0:8058 api:app
The else statement app.run() is not actually needed, but I keep it for reminding me about host, port etc.
Try setting the debug flag on the run command like so
gunicorn -c gunicorn.conf.py --debug testserver:app
and keep the DEBUG = True in your Flask application. There must be a reason why your debug option is not being applied from the config file but for now the above note should get you going.

Categories