Running python script on xampp - python

I googled this and tried everything but I could not run my test.py on apache.
I have updated httpd.conf file to AddHandler .py
#!/usr/local/opt/python/bin/python3.7
print("Hello World!")
When I open this file in browser I am getting this error
Error message:
End of script output before headers: test.py

Have you tried to use Flask instead? It start a server that you can access via browser.
Here you can find an Hello world tutorial, or also here.
First, you have to install Flask: pip install Flask.
Then the server code, saved in a python file, for example your_server.py, has to look like this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
You can run the script, then go to http://localhost:5000/ and you'll see the 'Hello World!' message.
Now you can modify the method hello() to do what you need, or create other method/operations.
The tutorial can give you more details, but this is the main concept.

Related

Terminal is showing error when running command "flask db init". Error: No such command 'db' [duplicate]

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

Why does my terminal not recognise pip or any Python modules that is recognised before? [duplicate]

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

updating flask code used for local host 127.0.0.1:5000

I am trying to develop a simple webpage using the Spyder IDE and Flask. I created the standard 'hello world' page.
From within Spyder I ran the script which I also tried running from the Windows Command Prompt/ Using the command python main.py I was able to launch my hello world webpage in http://127.0.0.1:5000/
I've gone back and updated the file to change the display text. Saved the file, restarted the code and the same content appears.
I have cleared the cache from the chrome browser I am already using.
I have opened this same address in other browsers (firefox and IE).
I created another version of this file in a different folder and also launched it.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hello, World! anyone?"
#app.route("/page2")
def salvador():
return "Hello, there"
if __name__ == "__main__":
app.run(debug=True)
No matter what I do, I get the same original hello world webpage.

Flask not displaying http address when I run it

I'm trying to run the Hello World using Flask framework :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello() -> str:
return 'Hell world from Flask!'
app.run()
Then I go to my cmd and I run my script according to the documentation:
set FLASK_APP = flaskhello.py
python -m flask run
And what I get is a grey window with a click me header and when I click it i get the X and Y but I don't get the http address on my cmd to run it on browser. What should I do to correct this ?
I've already installed flask correctly as it seems, but I'm not sure.
edit. I also tried creating a new venv and the same happens
You are mixing old and new documentation. You can lose the last line in flaskhello.py (app.run()). Then, don't pass the flask run command to python, but run it directly in the CMD. So not python -m flask run, but flask run.
I've tested your code and it is serving a page with Hell world from Flask!, are you sure your flask servers starts, do you see the following in the console:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [04/Aug/2019 13:35:44] "GET / HTTP/1.1" 200 -
Starting with Flask 0.11 there are multiple built-in ways to run a development server. The best one is the flask command line utility (https://flask.palletsprojects.com/en/1.1.x/server/)
export FLASK_APP= flaskhello.py
flask run

Can't get bottle to run on Elastic Beanstalk

I've got a website written in bottle and I'd like to deploy it via Amazon's Elastic Beanstalk. I followed the tutorial for deploying flask which I hoped would be similar.
I tried to adapt the instructions to bottle by making the requirements.txt this:
bottle==0.11.6
and replaced the basic flask version of the application.py file with this:
from bottle import route, run
#route('/')
def hello():
return "Hello World!"
run(host='0.0.0.0', debug=True)
I updated to this version as instructed in the tutorial, and when I wrote eb status it says it's green, but when I go to the URL nothing loads. It just hangs there. I tried the run() method at the end as it is shown above and also how it is written in the bottle hello world application (ie run(host='localhost', port=8080, debug=True)) and neither seemed to work. I also tried both #route('/hello') as well as the #route('/').
I went and did it with flask instead (ie exactly like the Amazon tutorial says) and it worked fine. Does that mean I can't use bottle with elastic beanstalk? Or is there something I can do to make it work?
Thanks a lot,
Alex
EDIT:
With aychedee's help, I eventually got it to work using the following application file:
from bottle import route, run, default_app
application = default_app()
#route('/')
def hello():
return "Hello bottle World!"
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
Is it possible that the WSGI server is looking for application variable inside application.py? That's how I understand it works for Flask.
application = bottle.default_app()
The application variable here is a WSGI application as specified in PEP 333. It's a callable that takes the environment and a start_response function. So the Flask, and Bottle WSGI application have exactly the same interface.
Possibly... But then I'm confused as to why you need that and the call to run.

Categories