Changing '?' to '&' in address bar - python

For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name.
More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name.
If I don't click SAVE, just refresh page, i'm getting error 404.
How can it be possible?
P.S My view function
#check_document_access_permission()
def notebook(request, is_embeddable=False):
if not SHOW_NOTEBOOKS.get():
return serve_403_error(request)
notebook_id = request.GET.get('notebook', request.GET.get('editor'))
is_yarn_mode = False
try:
from spark.conf import LIVY_SERVER_SESSION_KIND
is_yarn_mode = LIVY_SERVER_SESSION_KIND.get()
except:
LOG.exception('Spark is not enabled')
return render('notebook.mako', request, {
'editor_id': notebook_id or None,
'notebooks_json': '{}',
'is_embeddable': request.GET.get('is_embeddable', False),
'options_json': json.dumps({
'languages': get_ordered_interpreters(request.user),
'session_properties': SparkApi.get_properties(),
'is_optimizer_enabled': has_optimizer(),
'is_navigator_enabled': has_navigator(request.user),
'editor_type': 'notebook'
}),
'is_yarn_mode': is_yarn_mode,
})

I found error.
In frontend was JS function, which incorrectly changed url.

Related

ipywidgets button on click run next widget

I am building a small Jupyter Notebook widget to call a Rest API and get some data.
The user need to provide an auth token to be able to call the API. The auth token (JWT Token) will be provided to the user from a different interface. The API will respond with a json list of data which needs to be put into a combobox and then user can choose 1 which will be inserted into a new cell
The issue I am running into is that I am unable to tell the API call to wait for user to input the auth token and click on the submit button.
There are 2 actions happening here
Act 1 : Text Box and Button for the auth token. User puts the auth token in the text box and clicks submit.
Auth token gets put into a global variable by the button on clicked function
Act 2: Use the global variable to call the Rest API to get the JSON list of data
Put the list into a combobox
User chooses a specific value.
Dump that specific data into a new cell
import requests
import json
from IPython.display import Javascript, display
def click_get_auth_token(b):
global get_datasources_api_token
get_datasources_api_token = atok.value
return None
def show_wid():
global atok
atok = widgets.Text(
placeholder='Auth_Token',
description='Auth Token',
disabled=False
)
display(atok)
button = widgets.Button(description="Submit")
display(button)
button.on_click(click_get_auth_token)
return None
def click_get_auth_token():
show_wid()
headers = {}
resp = requests.get('http://localhost:5000/get_data', headers={"Authorization" : "Bearer " + get_datasources_api_token})
resp = resp.json()
dsr_list = resp['datasources']
opt_list = []
for dsr in dsr_list:
opt_list.append(dsr["name"])
print(opt_list)
global w
w = widgets.Combobox(
options= opt_list,
disabled=False,
ensure_option=True,
)
display(w)
button = widgets.Button(description="Get Data")
display(button)
button.on_click(click_get_datasources)
def click_get_datasources()
dataset = None
for dsr in dsr_list:
if(dsr["name"] == w.value):
dataset = dsr
encoded_code = (base64.b64encode(str.encode(dataset))).decode()
display(Javascript("""
var code = IPython.notebook.insert_cell_below('code');
code.set_text(atob("{0}"));
""".format(encoded_code)))
My code is probably all over the place and is needlessly complex.
At the moment it works as long as I hard code an auth token.
But I am unable to get the Rest call to wait for the user to paste the token.
Any help would be appreciated.
Thank you

Facebook get AdImage url from image_hash

My code (python-business-sdk):
account = AdAccount(ad_account_id)
img = account.get_ad_images(params={'hashes': ['6b709f0275d0bdf18fb78ef08492ee79'})[0]
print(img['url']) # doesnt work
primt(img[AdImage.Field.url]) # doesnt work
I do the request but get only id and hash in my img var (AdImage obj):
'{..., _json': {'hash': '6b709f0275d0bdf18fb78ef08492ee79', 'id': '36246837:6b709f0275d0bdf18fb78ef08492ee79'}}}
But i need the url of image, here's documentation with the fields (url is there) but i don't receive those or don't know how to get..
https://developers.facebook.com/docs/marketing-api/reference/ad-image#examples_read
Just add fields argument to get_ad_images

How to make only 1 refresh on multiple clicks python/django

I have a site using GCP python API, which is quite slow at making pull requests. So I have cached the area of the template using this data, and in the view I check if the cache is still active before making any more requests (not a copy n pasted code so if theres any typos ignore em :) )
def gcpProjectsView(request):
gcpprojects = None
cached_time = None
if cache.get(make_template_fragment_key('gcp')) is None:
cached_time=timezone.now()
gcpprojects = get_gcp_projects()
return render (request , 'gcp/gcpprojects.html', {'gcpprojects':gcpprojects,'last_update':cache_time})
To manually update the data, I have a refresh button that points to this view:
def refresh_gcp(request):
cache.delete(make_template_fragment_key('gcp'))
return redirect('gcpProjectsView')
The problem is that if the user clicks the refresh button 5 times the view makes 5 GCP Api calls, it needs to only do 1. How do I resolve this issue?
My suggestion would be to use a simple form with a button. Buttons can be disabled using simple javascript when clicked.
Because you're redirecting back to the same template in the view the button should be re-enabled again once it has 'refreshed'.
In this example snippet replace the action with whatever url routes to refresh_gcp.
<form method="GET" action="<url that points to refresh_gcp>">
<button type="submit" onclick="this.disabled = true;">Refresh</button>
</form>
This was the simplest solution I could think of that didn't involve implementing some sort of token validation for requests.
Use django session :
def refresh_gcp(request):
clicked = request.session.get("click")
if clicked:
return render(request,"your_html",{"disable":True})
# Set Button disable or not in your html by using context...
else:
request.session["click"]="user_click"
cache.delete(make_template_fragment_key('gcp'))
return render(request,"your_html",{"disable":False})

python self.session doesn't save data correctly

I'm developing a webapp using Google App Engine and Python.
I'm facing a strange problem and i don't know how to solve it and what causes it.
When I fill a form I send the data for checking them. If they aren't complete and some fields are missed the server send the form back with an advice "FILL ALL THE FIELDS!".
That's work pretty well.
What I'm trying to do is sending the form back with the "description" and "title" fields filled with what the user has written before submitting the form, so he must to fill only the unfilled fields (and he doesn't need to rewrite everything from the beginning).
That's the code:
class SaleAnnCheck(BaseHandler):
def post(self):
title = self.request.POST.get('title')
cat = self.request.POST.get('cat')
description = self.request.POST.get('description')
AcqOpt = self.request.POST.get('AcqOpt')
lat = self.request.POST.get('lat')
lng = self.request.POST.get('lng')
image1 = self.request.POST.get("file1", None)
image2 = self.request.POST.get("file2", None)
image3 = self.request.POST.get("file3", None)
logging.info("info sale announcment")
logging.info(title)
logging.info(cat)
logging.info(description)
logging.info(AcqOpt)
logging.info(lat)
logging.info(lng)
logging.info(image1)
logging.info(image2)
logging.info(image3)
self.session["ECommerceUser"]["description"]=description
self.session["ECommerceUser"]["title"]=title
logging.info('session')
logging.info(self.session["ECommerceUser"])
if title == '' or cat == None or description == '' or AcqOpt == None or lat == '' or lng == '':
error = 'empty'
urlR='/CreateSaleAnn?'+urllib.urlencode({'error':'empty'})
self.redirect(urlR)
class Create(BaseHandler):
def get(self):
error = self.request.get('error')
if error == 'empty':
logging.info('sbagliato')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'error':'FILL ALL THE MANDATORY FIELDS!', 'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
else:
logging.info('giusto')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
When I submit the form the content is checked by making an HTTP post request to a certain URL, handled by SaleAnnCheck.
Description and Title are saved in the session correctly (i checked it by printing the content of self.session["ECommerceUser"] in the logs). Then, if a field isn't filled, the server redirect again to the form page, by a GET request to a related URL.
The requests to that URL is handled by Create. But when i try to render the HTML template of the form (using jinja2) with the previous typed values of Description and Title the related text areas are not filled with that values.
It happens because self.session["ECommerceUser"]["description"] and self.session["ECommerceUser"]["title"] are empty, but they weren't when i checked them before (in SaleAnnCheck).
Why it happens? Any explanation? It's a weird problem and there aren't any tips or suggestion about on internet
This is because 'self.session' is not a Session, it's just a class variable and will not be readable outside the class. If you really want to use persistent sessions for storing variables, try something like this:
From the docs:
http://docs.python-requests.org/en/master/user/advanced/
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies')

Django/Python - check if the user uploads a file - if not, show an image

I have an input tag where the user has to upload a file. Right now if the user doesn't upload anything I do this in the main view:
if len(request.FILES) != 0:
data = request.FILES['some_file']
...do some work...
else:
return render(request, 'App/nofile.html' )
If there is no file I take the user the another page where it says that no file was uploaded and make him/her go back to the main page.
Is there a way that I can check if the user did not uploaded a file and not go to another page just show a PICTURE in the middle of the screen in that main page with the message?
NOT JUST A STRING MESSAGE, a picture with the message.
Maybe javascript is the answer but I know nothing about javascript.
Thanks in advance for any help.
There are two ways:
1) If you do validation on server side just like you do right now. It seems that you do it right, but you should use redirect instead of render if you handle POST data:
if len(request.FILES) != 0:
data = request.FILES['some_file']
...do some work...
else:
return redirect('/nofile/' {'foo': bar})
2) If you want client-side validation. Then you must prevent default submit action by javascript and check if file length equals 0. You can check this question or use this jQuery snippet:
$('form').submit(function(event){
validated = true;
if ($('#some_file_input').get(0).files.length === 0) {
validated = false;
console.log("No files selected.");
// Or some div with image showing
}
if (validated != true) {
event.preventDefault();
}
});

Categories

Resources