# symbol chopping the URL text Flask Application - python

I am using the following code to display the text on my browser:
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
#app.route('/api/v1.0/qanda/', methods=['GET'])
def people_api():
text = request.args.get('text'.replace('#',' ' ))
if text is None:
make_response(jsonify({'error': 'Missing text parameter'}), 400)
return text
app.run()
When I tried this:
http://127.0.0.1:5000/api/v1.0/qanda/?text=adam is my name
I got the output as:
adam is my name
But when I tried this:
http://127.0.0.1:5000/api/v1.0/qanda/?text=adam# is my name
I got the output as:
adam
I tried to replace the # symbol but it didn't work. I want to know, if I want to display my text in the browser using the above URL what I need to do? I want to display the complete text but only because of the # symbol this problem is arising, is what I suppose. Kindly, suggest me.

You can not put # as value in request parameter as like ?, &, /, &, =
If you really want to send # as in value of request parameter then you have to make it URL encoded to reach it to the server. Otherwise it will never reach to the server as you are expecting.
For encode of # you have to use %23.
As your requesting URL should be like http://127.0.0.1:5000/api/v1.0/qanda/?text=adam%23 is my name

The # symbol, like ? /, & and = has special meaning when used as part of the URL.
The # specifically is for identifying a named anchor in HTML; so the browser will not send it as part of the request.
Stick with space, or URL encode the string before you submit it.

Related

How to use password with special character in Basic Auth

I'm using Python Telegram Bot API https://github.com/python-telegram-bot/python-telegram-bot behind the proxy.
So my task is to set proxy using Basic Auth.
It works perfectly next way:
REQUEST_KWARGS = {
"proxy_url": "https://TechLogin:Pass#word!#192.168.111.38:5050/" # proxy example
}
updater = Updater(token=my_bot_token, request_kwargs=REQUEST_KWARGS)
But SysAdmin changed password for TechLogin and now it contains some special characters:
new_login = "-th#kr123=,1"
and requests library (or even urllib3) can't parse it:
telegram.vendor.ptb_urllib3.urllib3.exceptions.LocationParseError: Failed to parse: TechLogin:-th
Looks like it can't parse sharp symbol #
How can I escape it ?
You must use URL-encoding, as shown in this post:
Escaping username characters in basic auth URLs
This way the # in the password becomes %23
You can use URL encoded values.
ex:-
# = %23
You can encode values to URL here.
"-th#kr123=,1" = "-th%23kr123%3D%2C1"
"proxy_url": "https://TechLogin:-th%23kr123%3D%2C1#192.168.111.38:5050/"

Get user message on flask-assistant

I use flask-assistant on python 3 with dilaogflow as a webhook. I looked at the official documentation and I don't find how to get the user message ("queryText" on dialogflow json request).
I tried this with no success:
# -*- coding: utf-8 -*-
from flask import Flask
from flask_assistant import Assistant, ask, tell, context_manager, event
project_id='myproject_id'
app = Flask(__name__)
assist = Assistant(app, route='/', project_id = project_id)
#assist.action('Default Fallback Intent')
def manage_fallback(queryText):
print('*'*40,queryText)
speech='Running'
return tell(speech)
if __name__ == '__main__':
app.run(debug=True)
The print of queryText always return None, but when I inspect on the ngrok web interface (http://127.0.0.1:4040) , I can see the request.
And I want to know how canI get the user message from flask-assistant?
I also asked about this question on github and get the answer, so I will share for the others:
You can get the query text from the flask-assistant request object.
from flask_assistant import request
...
...
#assist.action('Default Fallback Intent')
def manage_fallback():
user_query = request['queryResult']['queryText']
speech = "You said " + user_query
return tell(speech)
The reason the value of queryText expected by your manage_fallback function is None is because the parameter name must match the entity type expected by the intent.
Parameters are used to receive parsed entities for an intent, not the full user query.

How to display images in html?

I have a working app using the imgur API with python.
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
for item in items:
print(item.link)
It outputs a set of imgur links. I want to display all those pictures on a webpage.
Does anyone know how I can integrate python to do that in an HTML page?
OK, I haven't tested this, but it should work. The HTML is really basic (but you never mentioned anything about formatting) so give this a shot:
from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
htmloutput = open('somename.html', 'w')
htmloutput.write("[html headers here]")
htmloutput.write("<body>")
for item in items:
print(item.link)
htmloutput.write('SOME DESCRIPTION<br>')
htmloutput.write("</body</html>")
htmloutput.close
You can remove the print(item.link) statement in the code above - it's there to give you some comfort that stuff is happening.
I've made a few assumptions:
The item.link returns a string with only the unformatted link. If it's already in html format, then remove the HTML around item.link in the example above.
You know how to add an HTML header. Let me know if you do not.
This script will create the html file in the folder it's run from. This is probably not the greatest of ideas. So adjust the path of the created file appropriately.
Once again, though, if that is a real client secret, you probably want to change it ASAP.

How to get data sent by cloud telephony service using django url?

I am planning to use cloud telephony to get sms data sent over Http. Service provider say this is how the format would be
http://domainname/location?mobilenumber=XXXXX&message=XXXXX&receivedon=MM/DD/YY HH:MM:SS AM/PM
How should i process this url. Is it just that i have to write an url pattern like this below?
url(r'^/location/(P?<mobilenumber>)\d+/(P?<message>)\w+P?<receicedon>)\d+$',app.project.views.widget,name='swidget')
try using url as:
url(r'^/location/',your_view,name='swidget')
When you use GET parametes like www.host.com/end_point/?message=value&something=value2 you don't have to set them in the url, instead just use url(r'^/end_point/, some_view)
and view like
def your_view(request):
mobilenumber = request.GET['mobilenumber']
message = request.GET['message']
receivedon = request.GET['receivedon']
# Do what you need
Hope it helps
Just write a view for the path /location, and inside the view use the request.GET dictionary to see the parameters in the URL:
def location_view(request):
mobilenumber = request.GET['mobilenumber']
...

Why non existing URL containing the sharp ("#") sign in Python/Flask aren't handled by the errorhandler

I'm building a Python/Flask (fully ajax, without full page reloading) web application and I change the content of my master page when the sharp ("#") sign on the url change (Ben Alman, HashChange event)
I would like to catch all Error-404 to append an error page in my master page
Taking the following code in consideration
from flask import Flask, redirect
#WebServerGatewayInterface
class WSGI():
def __init__(self):
self.app = Flask(__name__)
self.app.debug = True
wsgi = WSGI()
#wsgi.app.route("/")
def Home():
return "Home"
#wsgi.app.route("/Contact")
def Contact():
return "Contact"
#wsgi.app.errorhandler(404)
def PageNotFound(error):
return "PageNotFound"
if __name__ == '__main__':
wsgi.app.run(host='127.0.0.1', port=7777)
I would like to understand why when I add a non-exising URL after the sharp ("#") sign, it isn't trapped by the errorhandler ?
E.g.
127.0.0.1:7777
#It returns "Home"
127.0.0.1:7777/Contact
#It returns "Contact"
127.0.0.1:7777/Aasdasdasdasd
#It returns "PageNotFound"
127.0.0.1:7777/#/asdsaasdasdasdas
#It returns "Home", which is not right since this URL doesn't exist
127.0.0.1:7777/#!/asdsaasdasdasdas
#It returns "Home", not ok...
127.0.0.1:7777/#!/Contact
#It returns "Home", not ok...
Everything after the # forms the fragment identifier of a resource and is handled client side. In the normal course of operation, the fragment identifier is never sent to the server:
The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the web server
If a server is ever sent a fragment identifier in a URL, it must ignore this part of the URL. It is not part of the path, and thus Flask just sees 127.0.0.1:7777/ for all your sample URLs with a fragment.

Categories