Testing AJAX post in TestApp and Pyramid - python

I'm trying to write a test for an ajax view...The view is configured like so:
#view_config(name='new', context='resource.Events', renderer='json',
request_method='POST', xhr=True)
def event_view(self):
# ...
In my test, I want to create an ajax post so I try:
extra_environ = {'X_REQUESTED_WITH' : 'XmlHttpRequest'}
# also tried setting HTTP_X_REQUESTED_WITH
self.testapp.post('/events/new', params=post_params, extra_environ=extra_environ)
But the post never gets routed to my view. The request.is_xhr param never gets set to True.
Should be a simple answer somewhere, but I could not find it in any of the docs, or elsewhere. Can anyone recommend how to do this?
Thanks!

Looks like I wasn't casing 'xmlhttprequest' correctly. Needs to be:
extra_environ = {'HTTP_X_REQUESTED_WITH' : 'XMLHttpRequest'}
Found this in the code at:
webob/request.py line 472
Unfortunate to need to dig around in the code for this. Also surprised case matters.

In my case it was simply enough to set xhr=True in post request.
self.testapp.post('/events/new', params=post_params, xhr=True)

Related

Is it possible to inject python code in Kwargs and how could I prevent this user input

I'm at the moment in the middle of writing my Bachelor thesis and for it creating a database system with Postgres and Flask.
To ensure the safety of my data, I was working on a file to prevent SQL injections, since a user should be able to submit a string via Http request. Since most of my functions which I use to analyze the Http request use Kwargs and a dict based on JSON in the request I was wondering if it is possible to inject python code into those kwargs.
And If so If there are ways to prevent that.
To make it easier to understand what I mean, here are some example requests and code:
def calc_sum(a, b):
c = a + b
return c
#app.route(/<target:string>/<value:string>)
def handle_request(target,value):
if target == 'calc_sum':
cmd = json.loads(value)
calc_sum(**cmd)
example Request:
Normal : localhost:5000/calc_sum/{"a":1, "b":2}
Injected : localhost:5000/calc_sum/{"a":1, "b:2 ): print("ham") def new_sum(a=1, b=2):return a+b":2 }
Since I'm not near my work, where all my code is I'm unable to test it out. And to be honest that my code example would work. But I hope this can convey what I meant.
I hope you can help me, or at least nudge me in the right direction. I've searched for it, but all I can find are tutorials on "who to use kwargs".
Best regards.
Yes you, but not in URL, try to use arguments like these localhost:5000/calc_sum?func=a+b&a=1&b=2
and to get these arguments you need to do this in flask
#app.route(/<target:string>)
def handle_request(target):
if target == 'calc_sum':
func= request.args.get('func')
a = request.args.get('a')
b = request.args.get('b')
result = exec(func)
exec is used to execute python code in strings

Can't figure out how to return a Python dict/Json as xml using Spyne

I have fired up a WSGI application using Spyne for some SOAP services that I'm trying to build.
I'm absolutely new to SOAP and Spyne in general and I can't seem to figure out how to return a JSON/Python dict as XML. This is what I've done.
class Fruits(ServiceBase):
#rpc(_returns=Iterable(Unicode))
def fruitify(self):
fruits = {"apple" : "1", "orange" : ["2","3","4"]}
return fruits
I think the problem lies in the decorator I'm specifying using _returns.
I tried reading the docs again and again but couldn't figure it out.
The response I'm getting is something like:
<soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="lets_fruit">
<soap11env:Body>
<tns:fruitifyResponse>
<tns:fruitifyResult>
<tns:string>apple</tns:string>
<tns:string>orange</tns:string>
</tns:fruitifyResult>
</tns:fruitifyResponse>
</soap11env:Body>
</soap11env:Envelope>
As evident, it does not have any of my values associated to keys.
Has anybody done something similar and successfully implemented this before?
Thanks in advance!
Figured out guys.
I just had to change my _returns=Iterable(Unicode) to _returns=AnyDict.
Thanks!

Problems with django cookies

How do you properly set cookies in Django?
I have tried this:
re=HttpResponse('Hello world')
re.set_cookie('key','value')
and also this:
request.COOKIES['key']='value'
None of these are working and I have yet to figure out why.
Edit 1
Here is what my code looks like so far:
lang=UserData.objects.get(user_id=request.user.id)
lang.pref_language=request.POST.get('lang','')
re=HttpResponse('Hello world')
re.set_cookie('dddd',request.POST.get('lang','') )
request.COOKIES['ffff']=request.POST.get('lang','')
lang.save()
return HttpResponse('Updated')
so language is being saved every time function runs but cookies are not working properly.
Finally I figured out that the reason why cookies are not set is that I am nor returning my response object . Here is final version
re=HttpResponse('/')
re.set_cookie('language',request.POST.get('lang','') )
return re

Addition transactionSettings to a request object on Authorize.net (using sdk-python)

I am using Authorize.net's native python sdk. In their API documentation, it shows that you can nest a setting as follows:
transactionSettings
setting
settingName
settingValue
I have setup a ARBCreateSubscriptionRequest object, and am trying to set duplicateWindow to False.
request = apicontractsv1.ARBCreateSubscriptionRequest()
request.transactionSettings = {'setting': [{'settingName': 'duplicateWindow', 'settingValue': False}] }
That seems to have no impact.
What I am trying to do is override Authorize.net's default protection for duplicate transactions because I need to be able to submit multiple subscriptions for a single user.
Any thoughts on how to:
(1) properly set transactionSettings and/or
(2) override duplication error?
To remove the duplicate window protection you need to set it to zero:
request = apicontractsv1.ARBCreateSubscriptionRequest()
request.transactionSettings = {'setting': [{'settingName': 'duplicateWindow', 'settingValue': 0}] }
The way I solved this is that I had the list and dictionaries set incorrectly. Unfortunately, it took a lot of digging thru source code to figure this out because the documentation was not as clear as I would have hoped. Regardless, now that I found the solution, all is well:
request.transactionSettings = [{'setting': {'settingName': 'duplicateWindow', 'settingValue': False} }]

How would you adblock using Python?

I'm slowly building a web browser in PyQt4 and like the speed i'm getting out of it. However, I want to combine easylist.txt with it. I believe adblock uses this to block http requests by the browser.
How would you go about it using python/PyQt4?
[edit1] Ok. I think i've setup Privoxy. I haven't setup any additional filters and it seems to work. The PyQt4 i've tried to use looks like this
self.proxyIP = "127.0.0.1"
self.proxyPORT= 8118
proxy = QNetworkProxy()
proxy.setType(QNetworkProxy.HttpProxy)
proxy.setHostName(self.proxyIP)
proxy.setPort(self.proxyPORT)
QNetworkProxy.setApplicationProxy(proxy)
However, this does absolutely nothing and I cannot make sense of the docs and can not find any examples.
[edit2] I've just noticed that i'f I change self.proxyIP to my actual local IP rather than 127.0.0.1 the page doesn't load. So something is happening.
I know this is an old question, but I thought I'd try giving an answer for anyone who happens to stumble upon it. You could create a subclass of QNetworkAccessManager and combine it with https://github.com/atereshkin/abpy. Something kind of like this:
from PyQt4.QtNetwork import QNetworkAccessManager
from abpy import Filter
adblockFilter = Filter(file("easylist.txt"))
class MyNetworkAccessManager(QNetworkAccessManager):
def createRequest(self, op, request, device=None):
url = request.url().toString()
doFilter = adblockFilter.match(url)
if doFilter:
return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl()))
else:
QNetworkAccessManager.createRequest(self, op, request, device)
myNetworkAccessManager = MyNetworkAccessManager()
After that, set the following on all your QWebView instances, or make a subclass of QWebView:
QWebView.page().setNetworkAccessManager(myNetworkAccessManager)
Hope this helps!
Is this question about web filtering?
Then try use some of external web-proxy, for sample Privoxy (http://en.wikipedia.org/wiki/Privoxy).
The easylist.txt file is simply plain text, as demonstrated here: http://adblockplus.mozdev.org/easylist/easylist.txt
lines beginning with [ and also ! appear to be comments, so it is simply a case of sorting through the file, and searching for the correct things in the url/request depending upon the starting character of the line in the easylist.txt file.
Privoxy is solid. If you want it to be completely API based though, check out the BrightCloud web filtering API as well.

Categories

Resources