1)Geting error 404 The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
2)Unable to call data user wise as I have 25 user want to call data for single user
conn = pymysql.connect(host=None, user='root', passwd=None, db='db1')
heart_data = pd.read_sql('select * from heart',con = conn)
app = Flask(__name__)
#app.route('/HRV/<userid>/',methods = ['GET'])
def HRV(userid):
db = heart_data[heart_data['userId'] == userid]
return(db)`
if __name__ == "__main__":
`app.run(debug=True)`
Try to remove the trailing slash.
For exzample you have the following code:
#app.route('/projects/')
def projects():
return 'The project page'
#app.route('/about')
def about():
return 'The about page'
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash.
The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
Detail info see Unique URLs / Redirection Behavior — Flask 1.0.2 documentation
Related
assume the following:
Your model has: Products.slug
urls: path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
views: products = Products.objects.get(id=id, slug=slug)
Someone goes to /products/1/brazil-nuts/, and it goes to the right page.
But then someone copy/pastes the url wrong to: /products/1/brazil-nu/
Then you get a DoesNotExist error... Now you could "fix" this by not forcing the slug=slug argument in your query, but then the url is incorrect, and people could link from /products/1/brazil-nu-sjfhkjfg-dfh, which is sloppy.
So how would I redirect an incorrect url to the correct one with the same url structure as the correct one (only id and slug arguments), without relying on JavaScript's window.history.pushState(null, null, proper_url); every time the page loads?
I've already tried making the same url pattern to redirect, but since django uses the first pattern match, it won't work no matter where you put the url in your list.
Just update your view:
products_q = Products.objects.filter(id=id, slug__startswith=slug)
products_count = products_q.count()
if products_count == 1:
product = products_q.first()
return reverse_lazy('product_detail', args=[product.id, product.slug])
I have studied the code as follow in Cherrypy web development,
if returnpage != '':
raise cherrypy.InternalRedirect(returnpage)
else:
raise cherrypy.HTTPRedirect("/hqc")
Google doesn't help much in this case after I did some research.
I've checked from cherrypy's __doc__, but the documentation there is very terse.
>>>print(cherrypy.InternalRedirect.__doc__)
Exception raised to switch to the handler for a different URL.
This exception will redirect processing to another path within the site
(without informing the client). Provide the new path as an argument when
raising the exception. Provide any params in the querystring for the new URL.
>>> print(cherrypy.HTTPRedirect.__doc__)
Exception raised when the request should be redirected.
This exception will force a HTTP redirect to the URL or URL's you give it.
The new URL must be passed as the first argument to the Exception,
e.g., HTTPRedirect(newUrl). Multiple URLs are allowed in a list.
If a URL is absolute, it will be used as-is. If it is relative, it is
assumed to be relative to the current cherrypy.request.path_info.
If one of the provided URL is a unicode object, it will be encoded
using the default encoding or the one passed in parameter.
There are multiple types of redirect, from which you can select via the
``status`` argument. If you do not provide a ``status`` arg, it defaults to
303 (or 302 if responding with HTTP/1.0).
Examples::
raise cherrypy.HTTPRedirect("")
raise cherrypy.HTTPRedirect("/abs/path", 307)
raise cherrypy.HTTPRedirect(["path1", "path2?a=1&b=2"], 301)
See :ref:`redirectingpost` for additional caveats.
My questions are:
- Why bother with redirect when you can simply invoke another handler?
- What are some practical senarios for the two redirect exception respectively?
InternalRedirect is only handled in the server side, this means that the client would not be aware of that redirection, because in terms of the HTTP protocol that is mediating the session between the client and the server, nothing changed. By server side I mean ONLY CherryPy will be aware of the rediction, if you have some intermediate server (like an nginx reverse proxy) it would not see anything different.
For example if the client visited a url /page_one and then you used raise InternalRedirect('/page_two'), the client (browser) will receive the content from the /page_two handler in the /page_one url. If you raised a regular HTTPRedirect the server would end the first request with an HTTP status code of 303 (or any other status that you passed to the exception) and a Location header to /page_two. Then is the client who will initiate another request to /page_two, basically everybody will be aware of the redirection (more info about HTTP redirection). Most of the time this is the better alternative.
Additionally you could detect if the request came from a previous InternalRedirect by verifying the cherrypy.request.prev property. It will have the previous cherrypy.request object as its value or None.
For the sake of a possible (maybe not the best example) use of an InternalRedirect, checkout this production/beta example page, in addition I added a tool to prohibit the client to reach to handlers directly.
The client will see a different content in the same page /. Note that the access log that CherryPy generates will log the url of the handler that end up handling the request, in this case you will see /_beta or /_production.
import random
import cherrypy
#cherrypy.tools.register('before_handler')
def private_handler():
"""End the request with HTTP 404 not found if the client
tries to reach the handler directly instead of being
internally redirected from other handler.
"""
if cherrypy.request.prev is None:
raise cherrypy.NotFound()
class MainApp:
#cherrypy.expose
def index(self):
# 50/50 change of receiving production or the new SHINY beta page
use_beta = random.randint(0, 1)
if use_beta:
raise cherrypy.InternalRedirect('/_beta')
else:
raise cherrypy.InternalRedirect('/_production')
#cherrypy.tools.private_handler()
#cherrypy.expose
def _production(self):
return (
"<html>"
"<h2>{}</h2>"
"</html>"
).format(
"Welcome to our awesome site!"
)
#cherrypy.tools.private_handler()
#cherrypy.expose
def _beta(self):
return (
"<html>"
'<h1 style="color: blue">{}</h1>'
"<p>{}</p>"
"</html>"
).format(
"Welcome to our awesome site!",
"Here is our new beta content..."
)
cherrypy.quickstart(MainApp())
How to Write a app yaml looks like htacess below
RewriteEngine on
# To append a query string part in the substitution string
RewriteRule ^([0-9a-z_/\-]+)/$ index.php\?p=$1 [QSA]
RewriteRule ^([0-9a-z_/\-]+)$ index.php\?p=$1 [QSA]
im doing so at app yaml for GAE Application was fail
as Dan mentioned, you will not be able to handle this all in the yaml, and will need to to handle the logic yourself, we do a simular thing in one of our project and will outline below our solution.
Our scenario is handling the old website article's URL structure, and trying to redirect them to the new URL structure.
In our yaml we register the pattern that we are looking to match on and direct it to a file where we will do the handling :
- url: (/.*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.*) (Pattern to match on)
script: publication.custom.redirector.app (Path to your .py that will have your handling in)
In our .py file we will catch that pattern and route it to our DefaultHandler that can then do any logic you need and redirect out:
( in our project this goes to /publication/custom/redirector.py )
import request
import settings
import re
class DefaultHandler(request.handler):
def get(self, pre, year, month, day, post):
post = re.sub('(.*[^0-9])[\d]{1}$', r'\1', post)
post = re.sub('[^0-9a-zA-Z-_\/]+', '', post)
path = post.split("/")[-1]
slug = "{0}-{1}-{2}-{3}".format(year, month, day, path)
article = self.context.call('pub/articles/get', slug=slug.lower())
if article:
self.redirect(article['pub_url'], permanent=True)
else:
self.render("pages/page-not-found/page-not-found.html")
app = request.app([
('/(.*)/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)', DefaultHandler)
], settings.gaext.config)
Hope this helps
The GAE app.yaml doesn't have a URL rewrite capability, it just parses the incoming request URL for request routing purposes, to determine which handlers to invoke.
One could maybe argue that the static_file handlers configuration has a somewhat similar capability, but it is only applicable to the static assets.
For the dynamic handlers you'd need to take care of such "rewrite" inside your app code. I'm quoting "rewrite" here as technically it's just a different way of parsing/interpreting the request URL inside your app code - the original, unchanged request URL will still be the one recorded by the GAE infra.
Im getting a different URL from what was initially displayed when tried on a browser
Facebook's docs say that a
Login Request
should have a format like this so using requests and urllib.parse I tried getting the response URL
import requests, facebook, logging
# REQUIRED AUTHENTICATION PARAMS
APP_ID = '1976346389294466'
APP_SECRET = '*************************'
REDIRECT_URI = 'https://www.facebook.com/connect/login_success.html/'
logging.basicConfig(level=logging.DEBUG)
perms = ['manage_pages','publish_pages']
fb_login_url = facebook.auth_url(app_id=APP_ID, canvas_url=REDIRECT_URI, perms=perms)
logging.debug("-----LOGIN URL:" + fb_login_url)
response = requests.get(fb_login_url, params={'response_type':'token'}, allow_redirects=True)
try:
response.raise_for_status()
except Exception as exec:
print("%(There was a problem)s" % (exec))
response = requests.get(response.url)
logging.debug("-----Response URL: "+response.url)
I'm expecting a Expected Return URL in the format of
https://www.facebook.com/connect/login_success.html#
access_token=ACCESS_TOKEN...
However, I'm only getting the correct response when I use a browser, on my program the response returns a URL of an entirely different format
https://www.facebook.com/login.php?skip_api_login=1&api_key=xxxxxxxxx&signed_next=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.11%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fwww.facebook.com%252Fconnect%252Flogin_success.html%252F%26scope%3Dmanage_pages%252Cpublish_pages%26response_type%3Dtoken%26client_id%xxxxxxxxxxx%26ret%3Dlogin%26logger_id%xxxxxxxxxxxxxxx&cancel_url=https%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html%2F%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%23_%3D_&display=page&locale=en_US&logger_id=xxx-xxxxx-xxxxx-xxxxxxxx
When I GET from the last redirect url from response.history,
the response returns a url to itself, so I'm not sure how to go about capturing
the initial value of the url such as when I use the browser
the thing is, Im not looking for anything else from the response besides the URL itself.
Additional Notes:
-in the browser after getting the response url I think javascript also changes the url to blank after a brief moment for security reasons
-When I enter the wrong formatted url to the browser, it redirects to the right value so is there something thats handling the response differently when I'm using the browser. If so, how do grab the right url?
Simply put
When I enter fb_login_url in browser I get...
https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN...
which is what I want, but
when I do it in the app with requests...
either with requests.get(fb_login_url).url
OR (because of a 303) something like
for r in response.history:
requests.get(r.url).url
i get the wrong url which is
https://www.facebook.com/login.php?skip_api_login=1&api_key=xxxxxxxxx&signed_next=1&n....
Let's say I want to get a zip file (and then extract it) from a specific URL.
I want to be able to use a wildcard character in the URL like this:
https://www.urlgoeshere.domain/+*+-one.zip
instead of this:
https://www.urlgoeshere.domain/two-one.zip
Here's an example of the code I'm using (URL is contrived):
import requests, zipfile, io
year='2016'
monthnum='01'
month='Jan'
zip_file_url='https://www.urlgoeshere.domain/two-one.zip'
r = requests.get(zip_file_url, stream=True)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall()
Thanks in advance!
HTTP does not work that way. You must use the exact URL in order to request a page from the server.
I'm not sure if this helps you, but Flask has a feature that works similarly to what you require. Here's a working example:
#app.route('/categories/<int:category_id>')
def categoryDisplay(category_id):
''' Display a category's items
'''
# Get category and it's items via queries on session
category =session.query(Category).filter_by(id=category_id).one()
items = session.query(Item).filter_by(category_id=category.id)
# Display items using Flask HTML Templates
return render_template('category.html', category=category, items=items,
editItem=editItem, deleteItem=deleteItem, logged_in = check_logged_in())
the route decorator tells the web server to call that method when a url like */categories/(1/2/3/4/232...) is accessed. I'm not sure but I think you could do the same with the name of your zip as a String. See here (project.py) for more details.