Django - Internationalisation and Google Maps api v3 - django

I have a Django app and have integrated some Google maps via the v3 api. After a week of discovery and playing around everything was working fine, until...
I changed the language on my app by clicking on a flag on a form that POSTS the action to /i18n/setlang/, which is what Django uses to change the language. Now the new language is showing up, but the maps aren't. In the Chrome debugger it's giving the following error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
StaticMapService.GetMapImage
The following is the Chrome debugger header content for the error:
1.
Request URL:
http://maps.googleapis.com/maps/api/js/StaticMapService.GetMapImage?1m2&1iNaN&2iNaN&2e2&3u8&4m2&1uNaN&2uNaN&5m3&1e3&2b1&5sen-US&token=128748
2.
Request Method:
GET
3.
Status Code:
[400 Bad Request]
400 Bad Request
4. Request Headers
1.
Referer:
http://127.0.0.1:8000/uns/uns_cities_form/Mu%C4%9Fla/
2.
User-Agent:
Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3
5. Query String Parameters
1.
1m2:
2.
1iNaN:
3.
2iNaN:
4.
2e2:
5.
3u8:
6.
4m2:
7.
1uNaN:
8.
2uNaN:
9.
5m3:
10.
1e3:
11.
2b1:
12.
5sen-US:
13.
token:
128748
6. Response Headers
1.
Content-Length:
1350
2.
Content-Type:
text/html; charset=UTF-8
3.
Date:
Sun, 06 Feb 2011 20:29:59 GMT
4.
Server:
staticmap
5.
X-XSS-Protection:
1; mode=block
If I set the language back to English all works fine again...
Ok, so there is nothing to do with any translation whilst loading the map, but I'm figuring that Django has changed something or other which is disrupting the Http request, although to be honest I have no idea what is going on. The following is the options and the call to the map
//Map Options
myOptions =
{
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID,
streetViewControl: false,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
}
//Create the map
map = new google.maps.Map(elem,myOptions);
Has anyone come across this, or can anyone throw some light on what might be happening?

I suspect Django's Format Localization could cause that.
When using Django's formatting system,
dates and numbers on templates will be
displayed using the format specified
for the current locale. Two users
accessing the same content, but in
different language, will see date and
number fields formatted in different
ways, depending on the format for
their current locale.
So depending on the language, it could use a dot or comma as separater. This could mean, that instead of 2 parameters, you actually got 4 parameters, because their decimal separator is a comma.
You could try to apply floatformat to prevent this from happening.
{{ city.0.0.latitude|floatformat:6 }},{{ city.0.0.longitude|floatformat:6 }}

Ok, got the core problem.
The Django latitude and longitude variables in my database are Decimal Fields. When I pass them from the template to the javascript function they are passing the first part of the decimal to the first argument and the second part of the decimal to the second argument instead of being two separate arguments.
for example... 36.620556 is a latitude in the following
onclick='showmap({{city.0.0.latitude}},{{city.0.0.longitude}});'
The function for showmap header is
showmap(lat,lng)
{...
However, lat and lan come out as follows
lat = 36 and lan = 620556
However the strange thing is that this doesn't happen if the default language is in English...
I'll play some more and see what I can find out...
SOLUTION:
As Reiner suggested it was the localisation that was the problem. I was getting commas in my decimal points so I wrote a quick template tag to replace the commas with a dot.
def fixlatlan(Object):
o = str(Object)
o = o.replace(",", ".")
return o
register.filter('fixlatlan', fixlatlan)

Related

How to use Regex to Genericise URLs in Azure App Insights

I'm trying to get average performance for API Calls in AppInsights, but don't want each separate call together with the parameter.
For example,
GET /api/questions/identity/00434514 I want GET /api/questions/identity
I've used https://regexr.com/ and come up with .*\a\p\i((\/[a-zA-Z]*)*), which works on the website, but AppInsights returns the IDs instead
The request is:
requests
| extend newUrl = replace_regex(url, #".*\a\p\i((\/[a-zA-Z]*)*)", #"*")
| summarize RequestsCount=sum(itemCount), AverageDuration=avg(duration) by newUrl
| order by AverageDuration desc
I'm expecting:
It starts with anything, following by 'api'
It then must have any number of '/' followed by alpha characters (repeated any number of times)
What part of my regex does it not like.

Power BI Advanced Editor - API Pagination Querying Resulting in Many Duplicate Results?

Ok I have been stuck on this for a few weeks now. I'm using the Front Email API for a business use case and have created an iterative function to (attempt to) get multiple pages of query results.
A quick overview of the API (endpoint) I'm using for context:
The "events" endpoint returns a list of records based on the parameters given in the query (like before/after/between certain times, types of events, etc.)
If the query results in more than 100 records, a "next" pagination link is generated for the next page(s) of results. There is no "page=n" parameter in the query URL, you only get the "next page" link from the response of the previous query (which is fairly unique)
A side note, the initial base_url for the first query, and the base_url of the "next page" link are two different urls (i.e. the initial call is https://api2.frontapp.com and the second is https://companynamehere-inc.api.frontapp.com), so this is taken into consideration in my querying function.
My environment looks like this:
As you can see, I query the initial URL using the external Func_Query_Front_API function, then begin the iteration; While the next page link is not null, keep feeding the next links returned from the previous calls back into the function to get the next page of results. I deconstruct the links given to the function into a base, relative path and body/params so that I can use this logic in both Desktop and Online Service (don't ask).
It's difficult to describe the results I get, because sometimes in the preview window, it just clocks and clocks and doesn't return any results with the API not being queried at all (confirmed from Postman and the rate limit remaining number in the response headers). When I do get results back, it's a massive list of records (way more than what I'm querying for/expecting to receive) that contains lots of duplicates. It's almost like the initial (or the second) query URL is being looped over and over again, but not the "next" page's links? Like it's somehow stuck in a semi-infinite loop while the "next" link is not null from the initial response only, so it just repeats the same query over and over again re-using the same "next" page link.
Now, unfortunately I cannot provide my bearer token for this API as it's private company info returned by the API, but I'm wondering if the issue is with my syntax in the code that someone can spot and steer me in the right direction. The querying function itself works when invoked on its own, and everything looks like it SHOULD work, but it's just not doing what I think the code is saying it should do.
I understand it's not much to go on, but I'm out of options in trying to debug this thing. Thanks!
UPDATE
I think what MIGHT help here is a working code written in Python that might help to translate what I'm looking for into Power BI, so I've provided a working code in Python below (again though, the bearer token is not provided, but the syntax should make things a bit clearer). The code closely resembles what I've already made in Power BI as well so hopefully this helps things a bit?
import requests
from time import sleep
########################################
# GLOBAL VARIABLES
########################################
_event_types_filter = "assign&q[types]=archive&q[types]=comment&q[types]=inbound&q[types]=outbound&q[types]=forward&q[types]=tag&q[types]=out_reply"
_after = 1667506000
_page_limit = 100
_bearer_token = "Bearer XXXXXXXXXXXXXXXXXXXXXXXXXX"
_init_base_url = "https://api2.frontapp.com"
_relative_path = "events"
_init_body = "limit=" + str(_page_limit) + "&q[after]=" + str(_after) + "&q[types]=" + _event_types_filter
_headers = {'authorization': _bearer_token}
_init_query_url = _init_base_url + "/" + _relative_path + "?" + _init_body
########################################
# FUNCTION - Query the API
########################################
def Func_Query_Front_API(input_url):
#print(input_url)
# Deconstruct the url into its separate parts
splitted_input_url = input_url.split("?")
input_url_base = splitted_input_url[0].replace("/events", "")
input_url_body_params = splitted_input_url[1]
# Query the API
response = requests.request("GET",
input_url_base + "/" + _relative_path + "?" + input_url_body_params,
headers=_headers)
# Get the "next" link from the response
next = response.json()["_pagination"]["next"]
# Return the response and the "next" link
return response, next
########################################
# MAIN PROGRAM START
########################################
# List to add the response data's to
Source = []
# Make the initial request and add the results to the list
init_response, next = Func_Query_Front_API(_init_query_url)
Source.append(init_response)
# While the "next" link(s) are not None, query the current
# "next" link for the next page(s) of the query
while next != None:
response, next = Func_Query_Front_API(next)
Source.append(response)
sleep(1)
print(Source)
print("Done!")

Django url not cannot find some UTF-8 usernames

i am experimenting with UTF-8 for usernames in a django app.
Django is Version 3.2.11
Python used is 3.9.4
Some users might have a profile visible to others and ther username in the url:
re_path("^u/(?P<username>\w+)/$", views.author_profile_view, name="author_profile_view"),
Normal Example works fine:
Browser shows -> /u/brainyChowder3/
Django shows -> GET /u/brainyChowder3/ HTTP/1.1" 200 10593
UTF-8 example 1 works also fine:
Browser shows -> /u/ɊȁⱲÒđΈⱦİĬd/
Django shows -> GET /u/%C9%8A%C8%81%E2%B1%B2%C3%92%C4%91%CE%88%E2%B1%A6%C4%B0%C4%ACd/ HTTP/1.1" 200 12508
But this UTF-8 does not work:
Browser shows -> /u/ɂáⱳ1⁄4%7Cĭğę
Django shows -> "GET /u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99 HTTP/1.1" 404 5585
The browser does show it strange, as he does not "translate" %7C to |, but that should be just optical?
Error shown is just
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99
The current path, u/ɂáⱳ1⁄4|ĭğę, didn’t match any of these.
In Django shell I can query this user:
>>> User.objects.get(username='ɂáⱳ1⁄4|ĭğę')
<User: ɂáⱳ1⁄4|ĭğę>
The URI decoding looks ok to me.
I hope someone can explain why this is happening to one UTF-8 string, but not the other. Or maybe even knows how to fix it? :-D
I know it may not be the smartes thing to allow all UTF-8 for usernames, but this is more an experiment for me.
Thanks
The reason this happens has nothing to do with UTF-8, but with the fact that the username contains a non-word character (a character not matched by \w): a character that is not allowed for the <str:…> path converter. You can work with a <path:…>:
path('u/<path:username>/', some_view, name='some_name')

Prevent URL encoding that is removing equals signs from URL

Working on a Django/React app. I have some verification emails links that look like the following:
https://test.example.com/auth/security_questions/f=ru&i=101083&k=7014c315f3056243534741610545c8067d64d747a981de22fe75b78a03d16c92
In dev env this works fine, but now that I am getting it ready for production, it isn't working. When I click on it, it converts it to:
https://test.example.com/auth/security_questions/f%3Dru&i%3D101083&k%3D7014c315f3056243534741610545c8067d64d747a981de22fe75b78a03d16c92/
This prevents react-router-dom from matching the correct URL, so a portion of the web application does not load properly.
The link is constructed using the following.
link = '%s/auth/security_questions/f=%s&i=%s&k=%s' % \
('https://test.example.com', 'ru', user.id, user.key)
Also, here is the url() that is catching the route:
url(r'^(?:.*)/$', TemplateView.as_view(template_name='index.html')),
These variables are supposed to be query parameters in a GET request. When you construct the link, you'll need to have a question mark in there somewhere separating the URL from the query string:
https://test.example.com/auth/security_questions/?f=ru&i=101083&k=7014c315...
^
|___ here
The conversion of = to url-encoded %3D etc is correct, and equivalent. Sometimes variables are part of the URL directly, but webapps don't use &-separated key/value pairs in that case.

'request' module not pinging web pages correctly when they are contained in list

I am using the request module to see if items in a list of words are an article at https://www.britannica.com. My current code is:
import requests
words = ['no', 'yes', 'thermodynamics', 'london', 'Max-Factor', 'be']
for word in words:
request = requests.head('https://www.britannica.com/topic/' + word.lower())
if request.status_code == 200:
print(">EXISTS")
print('https://www.britannica.com/topic/' + word.lower())
print("<")
else:
print(">DOESNT EXIST")
print('https://www.britannica.com/topic/' + word.lower())
print("<")
'Be' is the only string that prints 'EXIST', but 'thermodynamics', 'london', and 'Max-Factor' also exists and the program prints 'DOESNT EXIST'. If I do the operation on thermodynamics alone, it correctly prints 'EXISTS'. What is the reason and possible work-around for the discrepancy? Possibly the loading times of the various webpages ('Be' having the smallest)?
Apparently, britanica.com uses redirects, probably for load balancing, so you'll often get status 301 instead of 200. The requests module can follow on redirects if you use:
request = requests.head('https://www.britannica.com/topic/' + word.lower(),
allow_redirects=True)