Is there a way to find out if the current URL for the webhandler contains a # ?
I can't get written out the URL when i use a #.
self.request.url returns only the base URL when a URL with # is GET on server.
I have also tried to send the rest of the URL as an argument and print that.
('/(.*)', MainHandler),
class MainHandler(webapp2.RequestHandler):
def get(self, args):
self.response.out.write(args)
This will not post anything on args argument when URL is GET with a # in the URL. For everything else it successfully writes the rest of the URL after the base. Example on what kind of URL i'm trying to show: http://instahashtag.appspot.com/#/14212311
Am i missing something here?
The URL fragment is handled by the browser and is not passed to the server. If you need to handle it you need to write client-side code (most likely in JavaScript).
Related
I'm new to Python and Flask, i need redirect along with arbitrary or full url, its working fine with the blow code.
but if the url has '/#/' in it then its not working, users are bookmarked these urls and i need to redirect to new domain as part of migration.
Example:
user url: http://127.0.0.1:5000/abc1/cba2/#/yyyy/2001
URL to be redirected: http://168.192.0.12:5000/abc1/cba2/#/yyyy/2001
Its not working since the there is # sign, Flask captures url only till # sign [/abc1/cba2/], because of this the redirection fails
How do i resolve this issue?
from flask import Flask, redirect
import json
def create_app():
app = Flask(__name__)
#app.route('/', defaults={'arbitrary': ''}, methods=['GET'])
#app.route('/<path:arbitrary>')
def red(arbitrary):
print (arbitrary)
url_substring = "/yyyy/"
if url_substring in arbitrary:
new_path = 'https://xxxx.com/' + arbitrary
print (new_path)
return redirect(new_path, code=302)
else:
return redirect("https://xxxx.com", code=302)
According to http specification, content after # sign can be accessed only by client. In your situation, you can read the omitted part after loading a sample page which sends ajax request with the omitted content after # from client side.
Please see here for reference. https://stackoverflow.com/a/9384407/4374376
Are you aware of what the # sign means in a URL?
If you must include it then you have to escape the sign.
URL should be: http://127.0.0.1:5000/abc1/cba2/%23/yyyy/2001
%23 represents the # sign.
Fragment Url's [whatever after #] will not be sent to server side, so JS is the only option, I have used NodeJS [Server side] and JS for this.
Once the customer click's the bookmarked URL it will reach to NodeJS from there it will be routed to the HTML page which got the JS to get the fragment URL and redirect accordingly.
The below JS will get the Fragment URL
var urlAddress = document.URL.substr(document.URL.indexOf('#')+1);
This is my first application using Flask and Python.
I am using below URL format to send a POST request from Arduino to the flask application running on Pythonanywhere server instance.
Valid POST request: 3 URL parameters
http://voyagers.pythonanywhere.com/senddata?node=1234&lat=18.5580&lng=73.8075
I need to block the request from further processing by validating the URL in some form. I want this to secure my app from un-authenticated POST requests.
Say something like this:Anything more than 3 URL Parameters
http://voyagers.pythonanywhere.com/senddata?node=324&lat=18.5580&lng=73.8075&a=c&a=d
How can I achieve this in Flask ?
Also suggest , If there is any better way which could be used to secure application from un-authorised requests.
You can get flask to validate the parameters and throw an error automatically if you are willing to switch from URL parameters (i.e. anything after the '?' symbol in the URL) to path parameters (i.e. anything that is in the Path HTTP header, or the part of the URL after the first '/' and abefore the '?').
Your example could look like this:
#app.route('/post/<int:node_id>/<float:lat>/<float:lng>', methods=['POST'])
def process_post_request(node_id, lat, lng):
# do some work
return your_result
Then you could send request to URL that would look for example like this: http://example.com/post/1234/-11.45/21.34
You can find more about this here: http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules
For securing access you can use some of the example snippets here: http://flask.pocoo.org/snippets/category/authentication/
I would recommend restricting access to HTTPS only and using the basic auth if you are just playing around. This is something you can do with a simple decorator as described here: http://flask.pocoo.org/snippets/8/
You will get a prompt in your browser asking you for username and password and browser will remember it for the duration of the session. Alternatively, you can set the username and password in base64 encoded form in the Authorization header: https://en.wikipedia.org/wiki/Basic_access_authentication
I am making a simple python API using Bottle. Everything is working fine until I provide the parameter to be something like http://sahildua.com/projects/. Even if I send a URL as a encoded string, it still shows the same error i.e. 404 Not Found.
#route('/expand-url/<url>', method='GET')
def expand(url = ""):
if url == "":
return {"success" : False}
What do I need to change in #route instruction to make it work? Or is there any other way of sending the URL as a parameter?
Your issue is caused by the fact that there are forward slashes '/' in the value you are sending to your route. Bottle is interpreting/parsing the API call correctly, just not with you're expecting.
With your current route setup, Bottle is interpreting your API call as sending the value projects/ to the route /expand-url/http://sahildua.com/(which doesn't exist - hence the 404 error), instead of sending the url value http://sahildua.com/projects/ to the route /expand-url/<url> - The forward slashes are mucking things up - so you need a different approach.
I suggest passing the url as a GET parameter instead of accepting it via the route url.
So your API call would look like curl -XGET http://APIURL/expand-url?url=http://sahildua.com/projects/.
Then you can retrieve the url in bottle using: url = request.query.get('url', ''). i.e.
#route('/expand-url', method='GET')
def expand():
url = request.query.get('url', '')
if url == "":
return {"success" : False}
This code is not tested but just to give you an idea.
I'm coming across a rather strange problem in a small app I've made for Google App Engine. This is not intended to be accessed by a browser but to provide a kind of rudimentary REST API for another system. This is the basic structure of the app:
import webapp2
class MainPage(webapp2.RequestHandler):
def post(self):
<do good stuff>
def get(self):
raise Exception("Cannot call this app through a get request")
app = webapp2.WSGIApplication([('/objviewer/', MainPage)],debug=True)
It works fine with this in my app.yaml:
- url: /objviewer/
script: gaeobjviewer.app
and with this code from a python script to call it:
encodedurl = urllib.urlencode({'tablename':tablename,'objid':objid})
# uploadservers[uploadkey] in the next line is a URL
response = urllib2.urlopen(uploadservers[uploadkey], data = encodedurl)
print response.read()
Now, in my app.yaml, suppose I add in a "secure: always" line:
- url: /objviewer/
secure: always
script: gaeobjviewer.app
The script promptly fails and claims it's being called with a get request. self.request.GET reports an empty dictionary.
Changing the protocol from http to https or vice versa in the urllib2.urlopen call makes no difference.
In the available literature on https I can find nothing about an empty GET request. Nor is there any reference to this in the GAE documentation that I can find. Why might this be occurring?
It turns out that setting the calling URL to https, and then removing the final slash (if you have one), will result in a post request being sent. I don't know why this is the case, but clearly it has something to do with redirects, as noted in Bryce Cutt's comment.
On GAE (Python) I'm trying to send a GET request from local javascript and on receipt of the request redirect to another page. This is my code:
Local Javascript sending the POST:
$.get("/editor");
The Python on GAE
class Editor(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render())
app = webapp2.WSGIApplication([('/', StartScreen), ('/editor', Editor)],
debug=True)
I can type in the url /editor in the url bar and it does take me there. Why does my javascript GET request not activate the Editor handler and open /editor?
I am not sure if I understand the problem, but still give it a try:
The current way to use jQuery.get() should call the server but throw away the response, so you will see nothing of it in the browser.
You want at least to do:
$.get("/editor", function(response) {
document.location.href = 'another page';
});
where another page is where you want to redirect to. Then this still throws away what you content you get from the server. (response will be some HTML ... I am not sure how you want to get a location from that.) So I wonder if a simple HTML-link would just do what you want.