Why might this link not be working...? - python

I'm rendering a bunch of posts on a page where a user can browse listings and click on one of them and be sent to a 'singles page' for more information on whatever product they clicked. This method works for every link EXCEPT for the first one.
Anytime I click on the very first link of the page, I get a Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. error.
The logic I have in place for the HMTL/jinja is (everything is closed off properly, I'm cutting some unnecessary code for the sake of brevity):
{% set i = 0 %}
{% for row in data %}
{% set i = i + 1 %}
<a href="/iLike/{{ i }}">
<li>content</li>
</a>
and my python code:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
try:
loc = session.get('loc')
transType = session.get('transType')
data = singlesQuery()
return render_template('single.html', loc=loc,transType=transType,data=data[num-1])
except Exception as e:
return (str(e))

There is no need to build URLs manually. The best way it to use flask's built-in function url_for:
{{url_for('single2', num=i)}}
There is also no need for calculating the i manually, becaue there is built-in loop.index and loop.index0:
{% for row in data %}
<a href="{{url_for('single2', num=loop.index)}}">
I believe this should always create a valid URL.

Related

django_embed_video module throws error "e doesn't look like a module path"

I have been 6 hours trying to figure out why doesn't the django_embed_video module work as supposed.
I followed the documentation. Created a model with VideoEmbed Field. Used it in template.html.
Added the following:
EMBED_VIDEO_BACKENDS = (
'embed_video.backends.YoutubeBackend',
)
to settings.py
All i am trying to achieve is to view a youtube video in my template, but i keep getting this error:
detect_backend(str(backend_or_url))
File "project\venv\lib\site-packages\embed_video\backends.py", line 61, in detect_backend
backend = import_string(backend_name)
File "project\venv\lib\site-packages\django\utils\module_loading.py", line 27, in import_stringraise ImportError("%s doesn't look like a module path" % dotted_path) from err
ImportError: e doesn't look like a module path
template.html
...
{% load static %}
{% load embed_video_tags %}
...
{% for tid, t in tests.items %}
<div class="embed-responsive embed-responsive-16by9"> <!-- Bootstrap responsive layout -->
{% video t.ytvideo.url %} <!-- iterate tests and get YT video of each test -->
</div>
{% endfor %}
Theory: There is an error in detecting the backend, but I can't seem to get it!
If you have a diifferent way to achieve embedding youtube video in website, it would be appreciated. I have tried embedding yt video with just snippet code copied from yt website, but i faced tons of errors on the front-end regarding the CORS policies.
I installed django CORS module and allowed origin to all websites, yet kept facing cookie issues along with other CORS policies not working, or getting yt video blocked by the browser for cookie tracking issues. Further help is appreciated. Thanks in advance.
EDIT:
Now the page loads successfully but the video doesn't appear.
Console logs: Some cookies are misusing the recommended “SameSite“ attribute
I tried the following solution but didn't work:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
What am i missing?

Python Flask Application not redirecting

I'm trying to create a list of clickable links to external URLs. My HTML file looks like this
<ul>
{% for post in posts %}
<li><a href={{url_for('go_to_reddit', url=post.url)}}>{{ post.title }}</a></li>
{% endfor %}
</ul>
and the python file like this
#app.route('/redirect/"<url>"')
def go_to_reddit(url):
print("Redirecting to ", url)
return redirect(url)
I keep getting the following error whenever I press on one of the links
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 know it's not reaching the redirect function even though it hits the URL since my console doesn't print anything.
I don't think you can have quotes in a route parameter i.e. #app.route('/redirect/"<url>"') should be #app.route('/redirect/<url>') . Put another way, try dropping the quote around <url>
If you can't have quotes in a url parameter and you need to pass a complete url, then you should consider passing it as a query parameter e.g. /redirect/?link=post.url. Then in your handler for the route, you will do url = request.values.get('link', None)

Rendering pandas DataFrame to html on Flask

Can anyone give me some tips or links to investigate how to remedy a df.describe() in a web browser thru a flask app?
For example if I print(df.describe()) in IPython this comes thru in a nice format:
kW
count 28219.000000
mean 134.723654
std 46.849081
min 24.300000
25% 91.300000
50% 135.900000
75% 168.600000
max 313.900000
But if I attempt this with a render template pass the data as string::
maxStatsStr = str(df.describe())
resp = make_response(render_template('table.html',
maxStatsStr=maxStatsStr))
return resp
To the front end HTML file with Jinja syntax:
<p>{{maxStatsStr}}</p>
This shows up in the browser
kW count 34880.000000 mean 79.687947 std 42.909287 min 12.200000 25% 38.800000 50% 73.400000 75% 113.200000 max 292.800000
Would a better method be creating like a table somehow, and using a for loop with Jinja to display the data? On the backend I just dont know how to prepare a df.describe() to be rendered as a table, like this below:
{% for table in tables %}
{{ table|safe }}
{% endfor %}
FINAL CODE USED
statsInfoStr = df.describe().to_html()
resp = make_response(render_template('table.html',
maxDateStr=maxDateStr,
tables=[statsInfoStr], titles=df.describe().T))
return resp
table.html jinja to loop over data:
<h2>Summary Statistics</h2>
{% for table in tables %}
{{ table|safe }}
{% endfor %}
</body>
</html>
First, you can utilize the pd.DataFrame.to_html method to get the frame converted to html.
You might even use the Styling Guide to pretty it up before converting to html.
Then, you probably want to use the render_template_string function instead.
e.g.:
def some_flask_func(...):
# ... your other codes ... #
# If you just want to get the vanilla structure:
df_html = df.describe().to_html()
# or, if you want to use Styler instead:
df_html = df.describe().style.apply(some_style_func).render()
# render directly from string:
resp = make_response(render_template_string(df_html)
return resp

Pass variable %s to href with Google App Engine

I am trying to pass my variable id to the href
{% set id = p.key().id() %}
<a href="/blog/editpost/%s" % id > Edit Post</a>
But it is showing up as /blog/editpost/%s instead of /blog/edit/93090902902 where the number is the post id.
I know how to do it using ?postId = and also
Edit Post
But with that method I have to get the last thing in the url path in my python file. I want to instead get the id request object.
What I am asking here is how can I use %s to send my variable id instead of using some other way of sending it?

django views.py to call another python script

I'm new to Django. Please help me with the below.
I have a User form who provides URL1 and URL2.. These URLs need to be passed to another Python script[redirects.py] which will do the Validation to check whether they are in a valid URL format and return the Message to the User.
Now my question is how to write my views.py so as to get this done. I got to know that we can import the redirects.py in my views.py and call it. But I'm not aware of how to print the messages in my browser. Please help. Let me know if any more info is required.
def shortcuts_process(request):
print request.POST
return HttpResponse("Source is %s\nDestination is %s" % (request.POST['source'],request.POST['destination']))
Update :
This is my script overview. I have got a python script[redirects.py] in my system which accepts Source and Destination URLs. Once accepted, it validates whether they are in URL format, then takes backup, then add them into .htaccess and display the line added to the file. While doing all this, it keeps intimating the User with the information on whats happening in the script.
Now I have made the django to create a web portal which provides the User to input source and Destination. Now i want to call the script from views.py and print all those redirects.py Script output in User's web browser.
Please help me in getting this, I have spent an entire day looking for this answer. Thanks.
Update 2:
Please let me know why the below is not getting displayed in my browser
From views.py
def shortcuts_process(request):
if 'source' in request.POST and 'destination' in request.POST and request.POST['source'] and request.POST['destination']:
src=request.POST['source']
desti= request.POST['destination']
my_result=process_input(src,desti)
return render_to_response('results.html',{'result': my_result}
From results.html :
<html>
<head>
This is the result page to User
</head>
<body>
<ul>
{% for each_line in result %}
<p>{{ each_line }}</p>
{% endfor %}
</ul>
<p>
I'm supposed to be printed</p>
</body>
</html>
From browser output :
This is the result page to User
I'm supposed to be printed
From Linux prompt :
[10/Jun/2013 04:41:11] "GET /redirects HTTP/1.1" 200 727 [10/Jun/2013
04:41:14] "GET /choice?selection=shortcuts HTTP/1.1" 200 817 The URL
is not in the right format The URL is not in the right format
[10/Jun/2013 04:41:18] "POST /shortcuts.conf HTTP/1.1" 200 125
So now my question, why the Message The URL is not in the right format is not getting displayed on browser rather it displays in Linux prompt. Please help. Thanks
Whatever string you want to display in the browser, return it in the HttpResponse.
You could try something like:
#validation.py
def validate(url1, url2):
# perform validation here
if valid:
return "urls are valid"
else:
return "urls are invalid"
#views.py
def shortcuts_process(request):
print request.POST
url1 = request.POST.get('url1', '')
url2 = request.POST.get('url2'. '')
return HttpResponse(validate(url1, url2))
Hope that helps.
For form validation, please refer to Chapter 7 in the django book (http://www.djangobook.com/en/2.0/chapter07.html)
Thanks all.. I managed to get the answer.
Rather having my function validate_url to print the values, changing it to return has given me the desired result.
I'm being so dumb to find this out. Failure is the stepping stone of Success !! :O)

Categories

Resources