I am new in python. I am trying to deploy python code on apache server for i.e i have created flask api. So for apache i have installed XAMPP and changed my httpd.conf to execute python on apache. It works well!! Here is code example which is working
Code working:
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
print("Content-type: text/html\n")
print ("Hello Python Web Browser!! This is cool!!")
But when I tried to import that through 500 Error, Here is the code
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'testing'
if __name__ == '__main__':
app.run(debug = True)
flask is installed on my environment (myproject). When I run through command like python test.py and it works.
Flask has it's own development web server.
Using python myfile.py which will work properly as a webserver (no need for apache on development).
If you still want do deploy on Apache, Flask have some info on how to do so, docs: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
Special attention to this: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/#creating-a-wsgi-file
Related
I want to know the correct way to start a flask application. The docs show two different commands:
$ flask -a sample run
and
$ python3.4 sample.py
produce the same result and run the application correctly.
What is the difference between the two and which should be used to run a Flask application?
The flask command is a CLI for interacting with Flask apps. The docs describe how to use CLI commands and add custom commands. The flask run command is the preferred way to start the development server.
Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi.
As of Flask 2.2, use the --app option to point the command at your app. It can point to an import name or file name. It will automatically detect an app instance or an app factory called create_app. Use the --debug option to run in debug mode with the debugger and reloader.
$ flask --app sample --debug run
Prior to Flask 2.2, the FLASK_APP and FLASK_ENV=development environment variables were used instead. FLASK_APP and FLASK_DEBUG=1 can still be used in place of the CLI options above.
$ export FLASK_APP=sample
$ export FLASK_ENV=development
$ flask run
On Windows CMD, use set instead of export.
> set FLASK_APP=sample
For PowerShell, use $env:.
> $env:FLASK_APP = "sample"
The python sample.py command runs a Python file and sets __name__ == "__main__". If the main block calls app.run(), it will run the development server. If you use an app factory, you could also instantiate an app instance at this point.
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
Both these commands ultimately start the Werkzeug development server, which as the name implies starts a simple HTTP server that should only be used during development. You should prefer using the flask run command over the app.run().
Latest documentation has the following example assuming you want to run hello.py(using .py file extension is optional):
Unix, Linux, macOS, etc.:
$ export FLASK_APP=hello
$ flask run
Windows:
> set FLASK_APP=hello
> flask run
you just need to run this command
python app.py
(app.py is your desire flask file)
but make sure your .py file has the following flask settings(related to port and host)
from flask import Flask, request
from flask_restful import Resource, Api
import sys
import os
app = Flask(__name__)
api = Api(app)
port = 5100
if sys.argv.__len__() > 1:
port = sys.argv[1]
print("Api running on port : {} ".format(port))
class topic_tags(Resource):
def get(self):
return {'hello': 'world world'}
api.add_resource(topic_tags, '/')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=port)
The very simples automatic way without exporting anything is using python app.py see the example here
from flask import (
Flask,
jsonify
)
# Function that create the app
def create_app(test_config=None ):
# create and configure the app
app = Flask(__name__)
# Simple route
#app.route('/')
def hello_world():
return jsonify({
"status": "success",
"message": "Hello World!"
})
return app # do not forget to return the app
APP = create_app()
if __name__ == '__main__':
# APP.run(host='0.0.0.0', port=5000, debug=True)
APP.run(debug=True)
For Linux/Unix/MacOS :-
export FLASK_APP = sample.py
flask run
For Windows :-
python sample.py
OR
set FLASK_APP = sample.py
flask run
You can also run a flask application this way while being explicit about activating the DEBUG mode.
FLASK_APP=app.py FLASK_DEBUG=true flask run
I have followed the google tutorial below and am able to run this on my google app engine no problem.
https://cloud.google.com/appengine/docs/standard/python3/building-app/writing-web-service
I only run into problems when I try to incorporate a kafka client in the main.py script. The main script is below and when all reference to kafka is commented out this script runs fine again in the app engine.
Can Kafka be used in an app engine? I have tried using both the internal and external kafka IP addresses on GCP with no luck... When I run "gcloud app deploy" with requirements.txt app.yaml and main.py in the same directory (as per tutorial), or even "python3 main.py" (for testing) the script hangs, there is no error message it just doesn't start the server. Again if Kafka references removed it runs fine. Kafka is running fine in the GCP project - can pub and sub from ssh terminals fine.
I have been able to make this Kafka setup work when run on a Google Compute Engine with the Flask app run directly from the VM - (running directly from the VM not using gcloud terminal). Doing this seems to allow kafka to use the internal IP address and avoids any problems with external IP addresses and cross network difficulties that Kafka doesn't seem to like.
Please help!! (This is my first ever SOF question - so be kind and be very descriptive:) )
from flask import Flask, render_template, Response
from pykafka import KafkaClient
from pykafka.common import OffsetType
clientKafka = KafkaClient(hosts='10.128.0.3:9092')
app = Flask(__name__)
topick = clientKafka.topics['gps_new']
producer = topick.get_sync_producer()
#app.route('/')
def index():
return(render_template('index.html'))
#app.route('/topic/gps_new/')
def get_messages():\
def events():
for i in
clientKafka.topics["gps_new"].get_simple_consumer(auto_offset_reset=OffsetType.LATEST,reset_offset_on_start=True):
yield 'data:{0}\n\n'.format(i.value.decode())
return Response(events(), mimetype='text/event-stream')
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
# Flask's development server will automatically serve static files in
# the "static" directory. See:
# http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
# App Engine itself will serve those files as configured in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello!</h1>'
if __name__ == "__main__":
app.run(debug=True)
And I get this message:
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/
Why am I getting this error when I run Flask?
A previous version of the message read "Do not use the development server in a production environment."
For deploying an application to production, one option is to use Waitress, a production WSGI server.
Here is an example of using waitress in the code.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
Running the application:
$ python hello.py
Waitress also provides a command line utility waitress-serve. To use that, you can modify the code to the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
def create_app():
return app
Then we can use waitress-serve as the following:
waitress-serve --port=8080 --call hello:create_app
And BTW, 8080 is the default port.
To validate the deployment, open a separate window:
% curl localhost:8080
<h1>Hello!</h1>%
Or directly in your browser http://localhost:8080/.
Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
As of Flask 2.2, the development server always shows this warning, it is not possible to disable it. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. Use a production WSGI server instead. See the deployment docs from Flask for more information.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
That warning applies to the development server, not Flask itself. The Flask framework is appropriate for any type of application and deployment.
To avoid these messsages, inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think)
Enter the following commands to do flask run
$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP=hello.py
$ python -m flask run
source: For more
Try gevent:
from flask import Flask
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
#app.route('/api', methods=['GET'])
def index():
return "Hello, World!"
if __name__ == '__main__':
# Debug/Development
# app.run(debug=True, host="0.0.0.0", port="5000")
# Production
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Note: Install gevent using pip install gevent
This worked for me on windows:
$env:FLASK_APP="flask_project.py"
$env:FLASK_ENV="development"
flask run
flask_project.py is on the same path as my virtual environment.
SetUp
VirtualBox | Ubuntu Server 12.04.2
(flaskve)vks#UbSrVb:~/flaskve$ python --version
Python 2.7.3
ifconfig
192.168.1.100 (the bridge interface on which i interact with VirtualBox)
code I am trying to run.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host='192.168.1.100', port=8080, debug=True)
When I do
(flaskve)vks#UbSrVb:~/flaskve$ python start.py
(flaskve)vks#UbSrVb:~/flaskve$
It does not run or do anything, it just returns back to command prompt. Although I am running in debug=True mode.
I then made a new VirtualEnv and install bottle in that. When I tried to run helloworld it shows the same behaviour.
However I then started the python shell on the same virtualenv, imported bottle modules and ran
>>> from bottle import route, run
>>> run(host='192.168.1.100', port=8081, debug=True)
Bottle v0.11.6 server starting up (using WSGIRefServer())...
Listening on http://192.168.1.100:8081/
Hit Ctrl-C to quit.
What could be problem here ?
Even debug does not show anything.
Following link is the output of python -v start.py
http://paste.ubuntu.com/5713138/
The first example uses Flask, not bottle. Maybe you are confusing your code snippets here? :)
I'm having problems getting dependencies installed on Heroku. I have a Python app that I want to deploy but every time I try and load the site I get ImportError's for both flask and sqlalchemy. I get these same errors if I run: heroku run python and try and import the modules interactively. I'm very puzzled and can't seem to solve this issue I was hoping someone else would know a solution. The details of the relevant files are down below.
Profile:
web: python app.py
requirements.txt:
Flask==0.9
Jinja2==2.6
SQLAlchemy==0.7.9
Werkzeug==0.8.3
app.py:
import os, flask, sqlalchemy
from gateway import server
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
server.app.run(host='0.0.0.0', port=port)
EDIT: I ended up restarting my application by following the Heroku instructions step-by-step and then copying over all my old code. This seemed to fix the problem for me so my problems seem to be a weird edge case.
I think your error may be in the "from gateway import server". It's not clear to me what that line's doing, and that code doesn't work when I try to run it locally on my machine.
Here's similar code, but in a format that's more familiar to me - I've deployed this to Heroku successfully in the past:
import os
from flask import Flask
from flask import render_template
app = Flask (__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Can you run this code locally?
Check the Heroku Flash tutorial
https://devcenter.heroku.com/articles/python