I am new to django , I started working on an existing Vuejs/Django project to easily understand how things are working .
I wrote a new specific view in views.js
def hello(request):
print(req.body)
return HttpResponse('hello')
Then in urls.py I added the following:
path('hello/',views.hello,name='hello')
At first I tried sending a plain/text , but the print function shows the following
b''
I tried printing request.data but it says
WSGIRequest' object has no attribute 'data'
I tried sending a JSON and using the following :
body_string = request.body.decode("utf-8", "ignore")
data = json.loads(body_string)
Result :
Expecting value: line 1 column 1 (char 0)Expecting value:
or:
data = json.loads(request.data.get('_content'))
Result:
'WSGIRequest' object has no attribute 'data'
none of that seems to be working .
The app I am working on seems to be working fine but it has no specific URL that's way I am stuck as I have no example , even here I couldn't find anything that helps.
Related
I have the following test
def test_bulk_post(my_faker,factory):
snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}]
assert factory.post('/snippets/',snippets) == True
I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request.
Right now this gives me:
/venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart()
*** AttributeError: 'list' object has no attribute 'items'
so its not expecting a list.. But I want to give it one. How do I do that?
factory.post by default expects a key, value pairs that goes with multipart/form-data and not list hence error
You should probably set content_type='application/json' to pass data as JSON body
factory.post('/snippets/',snippets, content_type='application/json )
I am trying to get the Parent Epic / Feature for particular User Stories in Rally. However I am only getting the parent object and I am not sure how to parse it. I have tried dict and dir(object) to get field values but it did not work. I have also tried as following, but I keep on getting something like this instead of fields/values in Parent Object
pyral.entity.PortfolioItem_Capability object at 0x7ff848273850
CODE:
def get_hierarchy(server,username,password,workspace,project,release):
rally = Rally(server, username, password, workspace=workspace, project=project)
criterion = 'Release.Name = "'+release+'" AND Parent != None'
response = rally.get('HierarchicalRequirement',fetch="ObjectID,FormattedID,Name,AcceptedDate,Project,Release,ScheduleState,Parent,Description",query=criterion,limit=5000)
return response
for item in get_hierarchy("rally1.rallydev.com","some.email#address.com","Somepassword","Some Workspace Name","PROJECT NAME","Release Version"):
print item.FormattedID, item.Name, item.ScheduleState, item.Description, item.Parent.Name
The parent is also an object and you have to parse the parent similar to the user story. For a simplistic solution, keep using the dot format. Here is a code snippet that does something similar to the above that should give you a start.
queryString = '(Iteration.StartDate > "2017-08-31")'
entityName = 'HierarchicalRequirement'
response = rally.get(entityName, fetch=True, projectScopeDown=True, query=queryString)
for item in response:
print(item.FormattedID,
item.PortfolioItem.FormattedID,
item.PortfolioItem.Parent.FormattedID,
item.PlanEstimate)
I'm using Python 3.x but I don't see any reason it wouldn't translate to 2.7.
Alright, so I'm working on a scrapy based webcrawler, with some simple functionalities. The bot is supposed to go from page to page, parsing and then downloading. I've gotten the parser to work, I've gotten the downloading to work. I can't get the crawling to work. I've read the documentation on the Spider class, I've read the documentation on how parse is supposed to work. I've tried returning vs yielding, and I'm still nowhere. I have no idea where my code is going wrong. What seems to happen, from a debug script I wrote is the following. The code will run, it will grab page 1 just fine, it'll get the link to page two, it'll go to page two, and then it will happily stay on page two, not grabbing page three at all. I don't know where the mistake in my code is, or how to alter it to fix it. So any help would be appreciated. I'm sure the mistake is basic, but I can't figure out what's going on.
import scrapy
class ParadiseSpider(scrapy.Spider):
name = "testcrawl2"
start_urls = [
"http://forums.somethingawful.com/showthread.php?threadid=3755369&pagenumber=1",
]
def __init__(self):
self.found = 0
self.goto = "no"
def parse(self, response):
urlthing = response.xpath("//a[#title='Next page']").extract()
urlthing = urlthing.pop()
newurl = urlthing.split()
print newurl
url = newurl[1]
url = url.replace("href=", "")
url = url.replace('"', "")
url = "http://forums.somethingawful.com/" + url
print url
self.goto = url
return scrapy.Request(self.goto, callback=self.parse_save, dont_filter = True)
def parse_save(self, response):
nfound = str(self.found)
print "Testing" + nfound
self.found = self.found + 1
return scrapy.Request(self.goto, callback=self.parse, dont_filter = True)
Use Scrapy rule engine,So that don't need to write the next page crawling code in parse function.Just pass the xpath for the next page in the restrict_xpaths and parse function will get the response of the crawled page
rules=(Rule(LinkExtractor(restrict_xpaths= ['//a[contains(text(),"Next")]']),follow=True'),)
def parse(self,response):
response.url
I'm new with django and I try to implement a chat, using socketio. I used ://github.com/stephenmcd/django-socketio and I followed this tutorial: http://codysoyland.com/2011/feb/6/evented-django-part-one-socketio-and-gevent/
The example works well. Now I would like to integrate this chat inside the templates of my django app. I didn't find any tutorial about that.
So I tried to take the example, I put the html inside my template and I used the .py inside my view.
So here is the part of my views.py that is creating the problem:
buffer = []
socketio = request.environ['socketio']
if socketio.on_connect():
socketio.send({'buffer': buffer})
socketio.broadcast({'announcement': socketio.session.session_id + ' connected'})
while True:
message = socketio.recv()
if len(message) == 1:
message = message[0]
message = {'message': [socketio.session.session_id, message]}
buffer.append(message)
if len(buffer) > 15:
del buffer[0]
socketio.broadcast(message)
else:
if not socketio.connected():
socketio.broadcast({'announcement': socketio.session.session_id + ' disconnected'})
break
But when I go to my page I get this error message:
'NoneType' object has no attribute 'get_server_msg'
Exception Type: AttributeError
Exception Value:'NoneType' object has no attribute 'get_server_msg'
Exception Location: /Users/marc-antoinelacroix/virtualenv/lib/python2.7/site- packages/socketio/protocol.py in recv, line 41
Do you have any idea on how to fix that?
Thank you,
Inside of my Django view I am trying to retrieve results from my database and then pass them on to my template with the following code:
f = request.GET.get('f')
try:
fb_friends_found= UserProfile.objects.filter(facebookid__in=f).values('facebookid')
i = fb_friends_found[0] #To get the dictionary inside of the list
results = i['facebookid'] #To retrieve the value for the 'facebookid' key
variables = RequestContext (request, {'results': results })
return render_to_response('findfriends.html', variables)
I carried out the first three lines within the 'try' block using manage.py shell and this worked fine, printing the correct 'facebookid'.
Unfortunately I can't get it to work in my browser. Any suggestions?
Do you have a specific problem you're running into, such as an exception?
I feel like you should get some kind of exception if you have a try block without an except statement.
try:
# something
except Exception: # but be more specific
print "exception occurred"
Otherwise, the code looks good, and if nothing is rendering in your browser, I'd look into the template. Unless... you're hiding errors in your try block, in which case you should remove the try block and let the error occur to understand what's wrong.