Reputation: 3
I am implementing a simple Android app, that needs to send data to a webserver. I currently use a HttpUrlConnection to send the data via a POST request to a php script on the server.
$value1 = $_POST["value1"];
$value2 = $_POST["value2"];
The values are received like simplified shown above. In the app I use the url, where the script is saved on the server.
Is there a simple way to get this done with python too? Or are there just some more complex solutions?
I could only find multiple ways of sending request with python or exchanging data within the webserver. But nothing worked for my project.
Upvotes: 0
Views: 2248
Reputation: 142641
In Python the easier way to get POST
is to use Flask
and run it with built-in server.
script.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
value1 = request.form.get('value1')
value2 = request.form.get('value2')
return 'OK'
else:
return 'Use POST requests'
if __name__ == '__main__':
#app.debug = True
app.run(host='0.0.0.0', port=8000)
and run as
python script.py
and it will run server on port 8000
so you can connect http://myserver:8000/
But if you already run Apache
/nginx
with PHP
then this makes problem.
You can't run both servers on the same port 80
. It would need to run all with Apache
.
PHP
was created for web pages and Apache
has preinstalled module to run PHP
(and to run PHP frameworks like Laravel
) but usually it doesn't have module for Python
. It may install module to run Python or other module to run CGI or FastCGI (which means any executable script - Python, Perl, Bash, and even compiled C/C++) but this is very old method which needs different modules in Python - so rather it can't run Flask
- and probably nobody use it. Flask
, Django
, Bottle
is simpler to write code, has many built-in functions and code is cleaner and better organized - like in PHP frameworks.
Flask
and other Python web frameworks (like Django
, Bottle
) are created to run with WSGI severs like Gunicorn
. They use eventually Apache
only as proxy-server
and to serve static files like images, CSS. So to use Flask/Django on external server you would have to find server which is configured for Flask
, Django
, etc. like PythonAnywhere
In PHP
you can mix all in one file - code, HTML, SQL - so it can make big mess and people created frameworks like Laravel
to make it cleaner and better organized. In Python
you use at start framework so you would have to compare Flask
with PHP frameworks but not with pure PHP.
Upvotes: 1