I am following this tutorial initially I was trying to get a response using postman with the url
ec2-x-x-xxx-xx.eu-west-2.compute.amazonaws.com/:8080
but it would not return a response, so then I tried without the / at the end and it returned what I wanted, why is this happening as my flask route clearly has a / in it
My flask app looks like this
from flask import Flask
application = Flask(__name__)
#application.route("/")
def hello():
return "<h1 style='color:blue'>Hello There!</h1>"
if __name__ == '__main__':
application.run(host="0.0.0.0", port="8080")
The order of the parts of a URL is important.
The URL
ec2-x-x-xxx-xx.eu-west-2.compute.amazonaws.com/:8080
Is going to attempt port 80, and look for a path /:8080.
ec2-x-x-xxx-xx.eu-west-2.compute.amazonaws.com:8080/
Will attempt port 8080 and look for a path /
There are two different concepts that you are getting mixed up on here.
The line #application.route("/") defines the root of your site. That is the default entry point or path if you enter your site address in a browser without e.g /about at the end.
The address ec2-x-x-xxx-xx.eu-west-2.compute.amazonaws.com:8080 is a combination of the web server address and port, separated by a colon. You will not get a response if you alter this address. You could add a "/" after the 8080 to get to a particular page.
Related
I want my web to be able to handle URLs inside the rule,
just like:
http://127.0.0.1:5000/tiyee?url=https://tiyee.cn/iyu2
but getting an error:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I've tried with this code below but seems like it doesn't work
from flask import Flask, redirect
from tiyee import bypasser
app = Flask(__name__)
#app.route('/tiyee?url=<url>')
def _tiyee_redirect(url):
bypassed_json = bypasser(url)
return redirect(bypassed_json['bypassed_link'])
if __name__ == '__main__':
app.run(debug=True, port=5000)
Q: Is there a way to add URL inside the route rule?
example:
example.com/tiyee?url=https://tiyee.cn/iyu2 and get the https://tiyee.cn/iyu2
You are passing the url data in query. You will need to use request object to get the query value.
from flask import request
...
#app.route('/tiyee')
def _tiyee_redirect():
_url = request.args.get('url')
if _url is not None:
bypassed_json = bypasser(_url)
return redirect(bypassed_json['bypassed_link'])
So, I am trying to understand the digest authentication implementation with Python- Flask.
I did a simple test, I took the below code from the documentation,
from flask import Flask
from flask_httpauth import HTTPDigestAuth
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
auth = HTTPDigestAuth()
users = {
"john": "hello",
"susan": "bye"
}
#auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
#app.route('/', methods=['HEAD'])
#auth.login_required
def index():
return "Hello, %s!" % auth.username()
if __name__ == '__main__':
app.run()
The code runs.
I paste this URL(host:port) in same in POSTMAN(head method), it always returns 401.
I am lost and am trying to get it work.
What am I doing wrong here?
OK so here is what the problem is, the URL works fine in the browser but not in POSTMAN.
This is happening due to the name resolution in your case, e.g. 9mxlhm2
You need to make sure that it resolved that name, try and see if you can ping that name mentioned or else easiest fix just use **0.0.0.0**, if this is local.
Make sure the authorization info is mentioned when you are doing a HTTP request via postman. Under the request section there will be a Authorization section. See this image as an example.
To reproduce the problem i used localhost but it didn't work and it gives me an error with 401, as soon as i try 0.0.0.0 in the GET request via postman, it starts to work again. Hope this fixes your problem. Although the hostname for me works(as in my own hostname, e.g rajlocal)
I want to create web server, and listen now.
Server must have different functions for each endpoint (and method).
I want to get (e.g. to variable) parameters (and data if POST)
Respond to get (and POST if its possible)
Respond in JSON
Someone can help me with this?
PS: I will be run it on Heroku, and send requests to it via Roblox's HttpService
Below see examples of each of your requirements using the Flask lightweight web framework.
After that is a link to a short description of how to deploy to Heroku.
# app.py
from flask import Flask
from flask import request, render_template
app = Flask(__name__)
#app.route('/test-get-request-parameters')
def test_get_request_parameters():
# 1. different function per endpoint
# 2. GET parameter to variable
# 3. respond to GET
var = request.args.get('some_request_variable')
return render_template('hello_world.html')
#app.route('/test-post-method',methods=['POST'])
def test_post_method():
# 2. receive POST data
# 3. respond to POST
print(request.get_json())
return 'hello, world!'
#app.route('/test-get-or-post', methods=['GET','POST'])
def test_get_or_post():
# 4. respond in JSON
if request.method == 'POST':
d = {'hello':'world'}
return d # this will be JSON response
return render_template('test.html')
To deploy to Heroku you need a Procfile with something like this in it:
web: gunicorn app:app
And you can follow these instructions: https://devcenter.heroku.com/articles/getting-started-with-python
i follow the tutorial based on a service i wan't to use ( Drone Deploy) :
https://dronedeploy.gitbooks.io/dronedeploy-apps/content/server_example.html
i made a topic on their forum for this issue 2 days ago.( and repo on Github)
But maybe someone can help me here.
I got an issue with an Heroku server app i do.
i use Python and the Tornado module.
The fact is i got a 404 error
My terminal ( when test it localy ) ask me :
"WARNING:tornado.access:404 GET / (::1) 0.75ms"
so the "GET" function is not working , maybe because of HTTP access control (CORS) i try many fix , but none worked.
Maybe i made something wrong ,or forgot something.
update :
Recently someone of the Drone deploy said my tornado routes aren't being picked up by heroku.
After following many tutorial and read the Tornado documentation i have no idea how to routes this.
the url of the server : https://stardrone-server.herokuapp.com/
this the code :
import os
import requests
import tornado.ioloop
import tornado.web
GEOCODE_FMT = 'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={key}'
class GeocodeHandler(tornado.web.RequestHandler):
"""Proxy a call to the Google Maps geocode API"""
def set_default_headers(self):
# allow cross-origin requests to be made from your app on DroneDeploy to your web server
self.set_header("Access-Control-Allow-Origin", "https://www.dronedeploy.com")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
# add more allowed methods when adding more handlers (POST, PUT, etc.)
self.set_header("Access-Control-Allow-Methods", "GET, OPTIONS")
def get(self):
api_key = os.environ.get("MyApiKey")
address = self.get_query_argument("address")
url = GEOCODE_FMT.format(address=address, key=api_key)
# fetch results of the geocode from Google
response = requests.get(url)
# send the results back to the client
self.write(response.content)
def options(self):
# no body
self.set_status(204)
self.finish()
def main():
application = tornado.web.Application([
(r"/geocode/", GeocodeHandler)
])
port = int(os.environ.get("PORT", 5000))
application.listen(port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
Maybe i missed something.
Any help, advices are appreciated
Thanks
John
Latest update: The problem had indeed to do with permission and user groups, today I learned why we do not simply use root for everything. Thanks to Jakub P. for reminding me to look into the apache error logs and thanks to domoarrigato for providing helpful insight and solutions.
What's up StackOverflow.
I followed the How To Deploy a Flask Application on an Ubuntu VPS tutorial provided by DigitalOcean, and got my application to successfully print out Hello, I love Digital Ocean! when being reached externally by making a GET request to my public server IP.
All good right? Not really.
After that, I edit the tutorial script and write a custom flask application, I test the script in my personal development environment and it runs without issue, I also test it on the DigitalOcean server by having it deploy on localhost and making another GET request.
All works as expected until I try to access it from my public DigitalOcean IP, now suddenly I am presented with a 500 Internal Server Error.
What is causing this issue, and what is the correct way to debug in this case?
What have I tried?
Setting app.debug = True gives the same 500 Internal Server Error without a debug report.
Running the application on the localhost of my desktop pc and DigitalOcean server gives no error, the script executes as expected.
The tutorial code runs and executed fine, and making a GET request to the Digital Ocean public IP returns the expected response.
I can switch between the tutorial application and my own application and clearly see that I am only getting the error wit my custom application. However the custom application still presents no issues running on localhost.
My code
from flask import Flask, request, redirect
from netaddr import IPNetwork
import os
import time
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
# Custom directories
MODULES = os.path.join(APP_ROOT, 'modules')
LOG = os.path.join(APP_ROOT, 'log')
def check_blacklist(ip_adress):
ipv4 = [item.strip() for item in open(MODULES + '//ipv4.txt').readlines()]
ipv6 = [item.strip() for item in open(MODULES + '//ipv6.txt').readlines()]
for item in ipv4 + ipv6:
if ip_adress in IPNetwork(item):
return True
else:
pass
return False
#app.route('/')
def hello():
ip_adress = request.environ['REMOTE_ADDR']
log_file = open(LOG + '//captains_log.txt', 'a')
with log_file as f:
if check_blacklist(ip_adress):
f.write('[ {}: {} ][ FaceBook ] - {} .\n'
.format(time.strftime("%d/%m/%Y"), time.strftime("%H:%M:%S"), request.environ))
return 'Facebook'
else:
f.write('[ {}: {} ][ Normal User ] - {} .\n'
.format(time.strftime("%d/%m/%Y"), time.strftime("%H:%M:%S"), request.environ))
return 'Normal Users'
if __name__ == '__main__':
app.debug = True
app.run()
The tutorial code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, I love Digital Ocean!"
if __name__ == "__main__":
app.run()
Seems like the following line could be a problem:
log_file = open(LOG + '//captains_log.txt', 'a')
if the path its looking for is: '/var/www/flaskapp/flaskapp/log//captains_log.txt'
that would make sense that an exception is thrown there. Possible that the file is in a different place, on the server, or a / needs to be removed - make sure the open command will find the correct file.
If captains_log.txt is outside the flask app directory, you can copy it in and chown it. if the txt file needs to be outside the directory then you'll have to add the user to the appropriate group, or open up permissions on the actual directory.
chown command should be:
sudo chown www:www /var/www/flaskapp/flaskapp/log/captains_log.txt
and it might be smart to run:
sudo chown -r www:www /var/www