def get(self, request): response = HttpResponse(content_type='application/json') # user_id = request.META['jrn-user-id'] # currently not used in the API params_users_ids = request.query_params.get('ids', None) # get requested user ids from query params if params_users_ids: users_ids = params_users_ids.split(',') else: response.status_code = status.HTTP_400_BAD_REQUEST body = {'reason': 'expected users ids'} response.content = json.dumps(body) return response # get data of all user ids from request try: users_in_db = User.objects.filter(pk__in=users_ids) except Exception: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return response returned_users_list = list() for user in users_in_db: returned_users_list.append(convert_user_to_dict(user)) # generate response response.content = json.dumps(returned_users_list) return response
def followPath(request, charId, pathHash): resp = HttpResponse() gChar = GameCharacter.objects.get(id=charId) # TODO: Validate to make sure that character is owned by the requester gCellIds = pathHash.split(":") initAP = gChar.owner.apRemaining initCell = gChar.cell try: for cellId in gCellIds: gCell = GameCell.objects.get(id=cellId) if gCell != gChar.cell: moveChar(gChar, gCell) except Exception as e: # Rollback data gChar.owner.apRemaining = initAP gChar.cell = initCell # Return error page to caller resp.status_code = 400 resp.content = str(e) return resp resp.status_code = 200 resp.content = "" return resp
def test_iter_content(self): r = HttpResponse(['abc', 'def', 'ghi']) self.assertEqual(r.content, b'abcdefghi') #test iter content via property r = HttpResponse() r.content = ['idan', 'alex', 'jacob'] self.assertEqual(r.content, b'idanalexjacob') r = HttpResponse() r.content = [1, 2, 3] self.assertEqual(r.content, b'123') #test retrieval explicitly using iter and odd inputs r = HttpResponse() r.content = ['1', '2', 3, '\u079e'] my_iter = r.__iter__() result = list(my_iter) #'\xde\x9e' == unichr(1950).encode('utf-8') self.assertEqual(result, [b'1', b'2', b'3', b'\xde\x9e']) self.assertEqual(r.content, b'123\xde\x9e') #with Content-Encoding header r = HttpResponse([1,1,2,4,8]) r['Content-Encoding'] = 'winning' self.assertEqual(r.content, b'11248') r.content = ['\u079e',] self.assertRaises(UnicodeEncodeError, getattr, r, 'content')
def scrobble(request): nowtime = str(int(time.time())) lastfm_session = request.COOKIES.get("lastfm_session", "") lastfm_session_key = request.COOKIES.get("lastfm_session_key", "") lastfm_login = request.COOKIES.get("lastfm_login", "") artist = urllib2.quote(request.POST.get("artist", "Unknown Artist").encode("utf-8", "ignore").replace("'", "\'")) duration = urllib2.quote(request.POST.get("duration_ms", "360").encode("utf-8", "ignore")) song = urllib2.quote(request.POST.get("title", "Track 1").encode("utf-8", "ignore").replace("'", "\'")) url = "http://post2.audioscrobbler.com:80/protocol_1.2" req = urllib2.Request(url, u's=' + lastfm_session + '&a[0]=' + artist + '&t[0]=' + song + '&i[0]=' + str(nowtime) + '&o[0]=P&r[0]=&l[0]=' + duration + '&b[0]=&n[0]=&m[0]=') response = HttpResponse() try: data = urllib2.urlopen(req).read().strip() if data == "BADSESSION": lastfm_session = handshake(lastfm_login, lastfm_session_key) response.set_cookie("lastfm_session", lastfm_session, max_age=SESSION_LIFECYCLE) req = urllib2.Request(url, u's=' + lastfm_session + '&a[0]=' + artist + '&t[0]=' + song + '&i[0]=' + str(nowtime) + '&o[0]=P&r[0]=&l[0]=' + duration + '&b[0]=&n[0]=&m[0]=') data = urllib2.urlopen(req).read().strip() ans = "%s %s" % (data, "SECOND") else: ans = "%s %s" % (data, "FIRST") response.content = "%s %s" % (lastfm_session, ans) except: response.content = "FAIL" return response
def wrapper(request, *args, **kwargs): timedata = datetime.now() data = func(request, timestamp=timedata, *args, **kwargs) logger.debug("Raw response data for %r: %r" % (func.__name__, data)) response = HttpResponse() response["X-Weave-Timestamp"] = weave_timestamp(timedata) if settings.DEBUG and "debug" in request.GET: logger.debug("debug output for %r:" % func.__name__) if int(request.GET["debug"]) > 1: def load_payload(item): if "payload" in item: raw_payload = item["payload"] payload_dict = json.loads(raw_payload) item["payload"] = payload_dict return item if isinstance(data, list): data = [load_payload(item) for item in data] else: data = load_payload(data) response["content-type"] = "text/plain" response.content = json.dumps(data, indent=4) else: if request.META.get("HTTP_ACCEPT") == 'application/newlines' and isinstance(data, list): response.content = '\n'.join([json.dumps(element) for element in data]) + '\n' response["content-type"] = 'application/newlines' response['X-Weave-Records'] = len(data) else: response["content-type"] = "application/json" response.content = json.dumps(data) return response
def test_iter_content(self): r = HttpResponse(['abc', 'def', 'ghi']) self.assertEqual(r.content, 'abcdefghi') #test iter content via property r = HttpResponse() r.content = ['idan', 'alex', 'jacob'] self.assertEqual(r.content, 'idanalexjacob') r = HttpResponse() r.content = [1, 2, 3] self.assertEqual(r.content, '123') #test retrieval explicitly using iter and odd inputs r = HttpResponse() r.content = ['1', u'2', 3, unichr(1950)] result = [] my_iter = r.__iter__() while True: try: result.append(my_iter.next()) except StopIteration: break #'\xde\x9e' == unichr(1950).encode('utf-8') self.assertEqual(result, ['1', '2', '3', '\xde\x9e']) self.assertEqual(r.content, '123\xde\x9e') #with Content-Encoding header r = HttpResponse([1,1,2,4,8]) r['Content-Encoding'] = 'winning' self.assertEqual(r.content, '11248') r.content = [unichr(1950),] self.assertRaises(UnicodeEncodeError, getattr, r, 'content')
def run(req): r = HttpResponse() r["Access-Control-Allow-Origin"]="*" try: if req.method == "OPTIONS" or len(req.POST)==0: #FF3 trying to check if Cross Site Request allowed. return r else: #rpc request: fctname = req.POST["f"] payload = json.loads(req.POST["a"]) cid = req.POST["cid"] if cid == "0" or cid == 0: cid = datetime.datetime.now() signals.register_session.send("rpc", cid=cid,req=req) UR.CID = cid MODULE = sys.modules[__name__] if fctname in __EXPORTS: r.content = getattr(MODULE, fctname)(payload, req) return r else: assert False, "[PDF] method '%s' not found in __EXPORTS" % fctname r.content = UR.prepare_response({}, 1,"[PDF] method '%s' not found in __EXPORTS" % fctname) return r except IOError: logging.error("[rpc.views.run] IOError") r.content = UR.prepare_response({}, 1,"I/O Error") return r
def process_response(self, request, response): if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.REQUEST: self.prof.close() out = StringIO.StringIO() old_stdout = sys.stdout sys.stdout = out stats = hotshot.stats.load(self.tmpfile) stats.sort_stats('time', 'calls') stats.print_stats() sys.stdout = old_stdout stats_str = out.getvalue() self.q_all = self.mysql_stat() - self.q_before - 1 response = HttpResponse() if stats_str: response.content = "<pre>" + stats_str + "</pre>" response.content = "\n".join(response.content.split("\n")[:40]) response.content += self.summary_for_files(stats_str) if self.q_all > -1: response.content += u"<pre>-----MySQL stats-----\n\nКоличество запросов к базе: %s \n\n</pre>"%self.q_all os.unlink(self.tmpfile) return response
def save(request, element): response = HttpResponse() #print (element) #print (request.body) #print (request.META) if (request.user.is_authenticated()): #print "Save received!! from " try: #print request.body #Validate the element passed: Valid only tabs,bookmarks or history. validate_type(element) parsedData = json.loads(request.body) #parse the incoming data to json type. alreadyExists = [] for p in parsedData: p['user'] = request.user p['typeOf'] = element savedData = saveData(p) if (savedData['exists'] == True): alreadyExists.append(savedData['savedData']) if (len(alreadyExists) > 0): response['error'] = 'already_exists' response.content = json.dumps(parseData(alreadyExists)) response.content_type = 'application/json' except ValidationError: response = HttpResponseBadRequest() response['error'] = 'Bad Request' response.content = 'Bad Request. Only allowed: /save/tabs/ or /save/bookmarks or /save/history' else: response.status_code = 401 response['error'] = 'Unauthorized' response.content = 'Unauthorized' return response
def upload(req): r = HttpResponse() f = req.FILES["file"] id_ensemble = req.GET["id_ensemble"] id_source = req.GET["id_source"] id_folder = req.GET.get("id_folder", None) uid = UR.getUserId(req); logging.info("upload uid=%s, id_source=%s, id_ensemble=%s, id_folder=%s" % (uid,id_source,id_ensemble,id_folder)) url = "http://%s:%s/%s?id_ensemble=%s" %("localhost", "8080",f.name, id_ensemble) payload = {"url": url, "id_source": id_source, "id_folder": id_folder } if auth.canInsertFile(uid, id_ensemble, id_folder): #the followong data will be deleted in utils_pdf if an PDF error happens later... annotations.createSource(uid, payload) annotations.addOwnership(id_source, id_ensemble, id_folder) REPOSITORY_DIR = "%s/%s" % (settings.HTTPD_MEDIA, "/pdf/repository") f2 = open("%s/%s" % (REPOSITORY_DIR, id_source,),"wb") f2.write(f.read()) f2.close() basedir = dirname(dirname(abspath(__file__))) #do the rest in the background, so server remains responsive cmd = "(cd %s; python -m upload.jobs file_img %s >/tmp/uploadscript_%s.log 2>&1 &)" %(basedir, id_source, id_log ) logging.info(cmd) os.system(cmd) r.content = UR.prepare_response({}) else: r.content = UR.prepare_response({}, 1, "NOT ALLOWED to insert a file to this group") return r
def upvote(request, video_shortlink): """Add an upvote to a video.""" response = HttpResponse(mimetype='application/json') if video_shortlink in request.COOKIES: response.status_code = 403 response.content = json.dumps({'error': 'already voted'}) return response video = get_object_or_none(Video, shortlink=video_shortlink) if video is not None: try: video.upvote() except socket.timeout: log.warning('Timeout connecting to celery to upvote video ' 'shortlink: %s' % video_shortlink) response.status_code = 500 response.content = json.dumps({'error': 'celery timeout'}) else: response.set_cookie(str(video_shortlink), value='1', httponly=False, max_age=settings.VOTE_COOKIE_AGE) response.content = json.dumps({'success': 'success'}) else: response.status_code = 404 response.content = json.dumps({'error': 'video not found'}) return response
def run(req): r = HttpResponse() r["Access-Control-Allow-Origin"]="*" if req.method == "OPTIONS" or len(req.POST)==0: #FF3 trying to check if Cross Site Request allowed. #print "options request" return r else: #rpc request: #if settings.ENABLE_REMOTE_DEBUGGING: # import pydevd; pydevd.settrace() fctname = req.POST["f"] payload = json.loads(req.POST["a"]) cid = req.POST["cid"] if cid == "0" or cid == 0: cid = datetime.datetime.now() signals.register_session.send("rpc", cid=cid,req=req) UR.CID = cid MODULE = sys.modules[__name__] if fctname in __EXPORTS: r.content = getattr(MODULE, fctname)(payload, req) return r else: assert False, "[PDF] method '%s' not found in __EXPORTS" % fctname r.content = UR.prepare_response({}, 1,"[PDF] method '%s' not found in __EXPORTS" % fctname) return r
def create_plot_optional_tree(request): response = HttpResponse() # Unit tests fail to access request.raw_post_data request_dict = json_from_request(request) # The Django form used to validate and save plot and tree information expects # a flat dictionary. Allowing the tree and geometry details to be in nested # dictionaries in API calls clarifies, to API clients, the distinction between # Plot and Tree and groups the coordinates along with their spatial reference flatten_plot_dict_with_tree_and_geometry(request_dict) # The new plot/tree form requires specific field names that do not directly match # up with the model objects (e.g. the form expects a 'species_id' field) so this # helper function renames keys in the dictionary to match what the form expects rename_plot_request_dict_fields(request_dict) form = TreeAddForm(request_dict, request.FILES) if not form.is_valid(): response.status_code = 400 if '__all__' in form.errors: response.content = simplejson.dumps({"error": form.errors['__all__']}) else: response.content = simplejson.dumps({"error": form.errors}) return response try: new_plot = form.save(request) except ValidationError, ve: response.status_code = 400 response.content = simplejson.dumps({"error": form.error_class(ve.messages)}) return response
def elfinder_connector_mce(request): try: finder = api(settings.ELFINDER_MCE) except: response = {} response['error'] = 'Invalid backend configuration' return HttpResponse(json.dumps(response),mimetype='application/json') if request.POST: if "cmd" in request.POST and request.POST["cmd"] == "upload": request.POST['upload[]'] = request.FILES.getlist('upload[]') finder.run(request.POST) return HttpResponse(json.dumps(finder.httpResponse)) finder.run(request.GET) ret = HttpResponse(mimetype=finder.httpHeader["Content-type"]) if finder.httpHeader["Content-type"] == "application/json": ret.content = json.dumps(finder.httpResponse) else: ret.content = finder.httpResponse for head in finder.httpHeader: if head != "Content-type": ret[head] = finder.httpHeader[head] ret.status_code = finder.httpStatusCode return ret
def create_plot_optional_tree(request, instance): response = HttpResponse() # Unit tests fail to access request.body request_dict = json_from_request(request) # The Django form used to validate and save plot and tree # information expects a flat dictionary. Allowing the tree # and geometry details to be in nested dictionaries in API # calls clarifies, to API clients, the distinction between # Plot and Tree and groups the coordinates along with their # spatial reference flatten_plot_dict_with_tree_and_geometry(request_dict) # The new plot/tree form requires specific field names that # do not directly match up with the model objects (e.g. the # form expects a 'species_id' field) so this helper function # renames keys in the dictionary to match what the form expects rename_plot_request_dict_fields(request_dict) plot = create_plot(request.user, instance, **request_dict) if type(plot) is list: response.status_code = 400 response.content = json.dumps({'error': plot}) else: response.status_code = 201 new_plot = plot_to_dict(plot, longform=True, user=request.user) response.content = json.dumps(new_plot) return response
def delete_file(request): if request.method == 'POST': response = HttpResponse() if request.user.is_authenticated(): if request.POST['directory'] == '': filename = request.POST['file'] else: filename = request.POST['directory'] + '/' + request.POST['file'] try: file = UserFiles.objects.filter(user__username=request.user.username).get(file=('users/'+ str(request.user.username)+ '/'+filename)) file.delete() json_helper.delete_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/', filename, settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+filename) json_helper.logger(settings.MEDIA_ROOT+'log.txt', request.user.username, 'deleted file: ', filename) response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+ str(request.user.username)+'/file_list.txt')) response['Content-Type'] = 'application/json' response.status_code = 200 except UserFiles.DoesNotExist: response.content = "File does not exist" response.status_code = 495 else: response.content = "Failed to authenticate user" response.status_code = 497 return response else : return HttpResponse()
def create_instances(request): name = request.POST.get('name') # Ensure user selects a frame if not name: response = HttpResponse() response.status_code = 400 response.content = "Please select a frame" return response sceneId = request.POST['sceneId'] corpusId = request.POST['corpusId'] word = request.POST['word'] wordPosition = request.POST['wordPosition'] sentenceId = request.POST['sentenceId'] try: Instances.create(name, word, wordPosition, int(sceneId), int(sentenceId), int(corpusId)) response = HttpResponse() response.content = "Successfully created instance" response.status_code = 200 return response except ValueError as e: response = HttpResponse() response.content = "Encountered error with " + str(e) response.status_code = 500 return response
def get(self, request): response = HttpResponse(content_type='application/json') params_notes_ids = request.query_params.get('ids', None) if params_notes_ids: notes_ids = params_notes_ids.split(',') else: response.status_code = status.HTTP_400_BAD_REQUEST body = {'reason': 'expected notes ids'} response.content = json.dumps(body) return response try: notes = Note.objects.filter(pk__in=notes_ids) except Exception as e: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR body = {'reason': 'failed fetching notes data'} response.content = json.dumps(body) return response body = list() for note in notes: note_dict = build_note_dict(note) body.append(note_dict) response.content = json.dumps(body) return response
def ajax_loginsta(request): """ ajax_loginsta """ user = request.user logined = request.user.is_authenticated() template = "member/profile/ajax_userstate.html" data = { 'user': user, } if logined: rendered = render_to_string(template, data) response = HttpResponse() response['Pragma'] = 'no-cache' response['Cache-Control'] = 'no-cache' response['Expires'] = 0 response.content = rendered else: rendered ='' response = HttpResponseForbidden() response.content = rendered response['Content-Length'] = 0 return response
def download_jsonform(request, username, id_string): """ XForm JSON view. """ owner = get_object_or_404(User, username__iexact=username) xform = get_form({ 'user__username__iexact': username, 'id_string__iexact': id_string }) if request.method == "OPTIONS": response = HttpResponse() add_cors_headers(response) return response helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): response = HttpResponseForbidden(_(u'Not shared.')) add_cors_headers(response) return response response = response_with_mimetype_and_name( 'json', id_string, show_date=False) if 'callback' in request.GET and request.GET.get('callback') != '': callback = request.GET.get('callback') response.content = "%s(%s)" % (callback, xform.json) else: add_cors_headers(response) response.content = xform.json return response
def test_iter_content(self): r = HttpResponse(['abc', 'def', 'ghi']) self.assertEqual(r.content, b'abcdefghi') #test iter content via property r = HttpResponse() r.content = ['idan', 'alex', 'jacob'] self.assertEqual(r.content, b'idanalexjacob') r = HttpResponse() r.content = [1, 2, 3] self.assertEqual(r.content, b'123') #test retrieval explicitly using iter (deprecated) and odd inputs r = HttpResponse() r.content = ['1', '2', 3, '\u079e'] with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) my_iter = iter(r) self.assertEqual(w[0].category, DeprecationWarning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) result = list(my_iter) self.assertEqual(w[0].category, DeprecationWarning) #'\xde\x9e' == unichr(1950).encode('utf-8') self.assertEqual(result, [b'1', b'2', b'3', b'\xde\x9e']) self.assertEqual(r.content, b'123\xde\x9e') #with Content-Encoding header r = HttpResponse() r['Content-Encoding'] = 'winning' r.content = [b'abc', b'def'] self.assertEqual(r.content, b'abcdef') r.content = ['\u079e'] self.assertRaises(TypeError if six.PY3 else UnicodeEncodeError, getattr, r, 'content') # .content can safely be accessed multiple times. r = HttpResponse(iter(['hello', 'world'])) self.assertEqual(r.content, r.content) self.assertEqual(r.content, b'helloworld') # accessing the iterator works (once) after accessing .content self.assertEqual(b''.join(r), b'helloworld') self.assertEqual(b''.join(r), b'') # accessing .content still works self.assertEqual(r.content, b'helloworld') # XXX accessing .content doesn't work if the response was iterated first # XXX change this when the deprecation completes in HttpResponse r = HttpResponse(iter(['hello', 'world'])) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertEqual(b''.join(r), b'helloworld') self.assertEqual(r.content, b'') # not the expected result! # additional content can be written to the response. r = HttpResponse(iter(['hello', 'world'])) self.assertEqual(r.content, b'helloworld') r.write('!') self.assertEqual(r.content, b'helloworld!')
def process_exception(self, request, exception): """ @type request HttpRequest @type exception Exception """ env = "" if request.GET.has_key("__env"): env = request.GET["__env"] if env == "" and request.is_ajax(): env = "ajax" response = HttpResponse() response.status_code = 500 if env == "ajax" or env == "json" or env == "partial": response.creamed = True response.content = renderAjaxException(request, exception) elif env == "ajaxform": response.creamed = True response.content = render_to_string( "decorator/ajaxform.html", {"jsonData": renderAjaxException(request, exception)} ) else: logging.getLogger("cream").exception(exception) if DEBUG: raise exception response.content = render_to_string( "decorator/exception.html", {"request": request, "exception": exception} ) return response
def add_subframe(request): sf_name = request.POST.get('sf_name') frame_name = request.POST.get('frame_name') try: # Make sure frame exists with name sf_name subframe = Frames.objects.filter(name=sf_name) if(len(subframe) == 0): response = HttpResponse() response.status_code = 400 response.content = "No frame with name " + sf_name + " exists" return response FrameRelations.create(parent_frame_name=frame_name, child_frame_name=sf_name, relation_type="SUBFRAME") # Create corresponding frame element relations sf_elements = FrameElements.objects.filter(frame_name=sf_name) parent_element = FrameElements.objects.filter(frame_name=frame_name)[0] for element in sf_elements: # "Self" frame element not a part of subframe relation if(element.fe_name != 'Self'): FeRelations.create(parent_fe_name=parent_element.fe_name, child_fe_name=element.fe_name, parent_frame_name=frame_name, child_frame_name=sf_name, rel_type="SUBFRAME") response = HttpResponse() response.status_code = 200 response.content = "Successfully added subframe" return response except ValueError as e: response = HttpResponse() response.status_code = 500 response.content = "Encountered error with " + str(e)[:200] return response
def register(request): query_is_from_browser = True if request.method == 'POST': email = request.POST.get('email', '') password = request.POST.get('password', '') first_name = request.POST.get('first_name', 'Walter') last_name = request.POST.get('last_name', 'White') if request.path[1:4] == 'api': query_is_from_browser = False resp = HttpResponse(mimetype='application/json') if not validate_form(email, password, first_name, last_name): if not query_is_from_browser: resp.content = json.dumps(LOGIN_RESPONSE_DICT['3']) resp.status_code = 400 return resp request.session['error'] = '3' return HttpResponseRedirect('/user/landing/') user = register_user(email, password, first_name, last_name) if user != None: create_default_groups(user) if not query_is_from_browser: resp.content = json.dumps(get_api_key(user)) resp.status_code = 200 return resp response = login_user(request, email, password) if response == USER_LOGGED_IN: request.session['error'] = '0' return HttpResponseRedirect('/tasks/main/') request.session['error'] = '4' return HttpResponseRedirect('/user/landing/')
def update_sfel_relations(request): sf_name = request.POST.get('sf_name') frame_name = request.POST.get('frame_name') parent_fes_string = request.POST.get('parent_fes') child_fes_string = request.POST.get('child_fes') # Arrays of frame element names of frames involved in relation parent_fes = json.loads(parent_fes_string) child_fes = json.loads(child_fes_string) try: # Update each frame element relation size = len(parent_fes) for i in range(size): parent = parent_fes[i] child = child_fes[i] relation = FeRelations.objects.get(parent_frame__name=frame_name, child_frame__name=sf_name, rel_type="SUBFRAME", child_fe_name=child) frame_element = FrameElements.objects.get(frame_name=frame_name, fe_name=parent) relation.parent_fe = frame_element relation.parent_fe_name = parent relation.save() response = HttpResponse() response.status_code = 200 response.content = "Successfully updated frame element relations" return response except ValueError as e: response = HttpResponse() response.status_code = 500 response.content = "Encountered error with " + str(e)[:200] return response
def add_frameelement(request): fe_name = request.POST.get('fe_name') frame_name = request.POST.get('frame_name') try: # Check if this frame already has frame element with same name fes_with_name = FrameElements.objects.filter(frame_name=frame_name, fe_name=fe_name) if(len(fes_with_name) > 0): response = HttpResponse() response.status_code = 400 response.content = "Another frame element already has this name" return response frame = Frames.objects.get(name=frame_name) new = FrameElements(frame=frame, frame_name=frame_name, fe_name = fe_name, core_status = "CORE", framenet_id=None) new.save() response = HttpResponse() response.content = "Successfully added frame element" response.status_code = 200 return response except ValueError as e: response = HttpResponse() response.content = "Encountered error with " + str(e) response.status_code = 500 return response
def delete_subframe(request): sf_name = request.POST.get('sf_name') frame_name = request.POST.get('frame_name') try: # Delete subframe relation sfToDelete = FrameRelations.objects.get(relation_type="SUBFRAME", parent_frame_name=frame_name, child_frame_name=sf_name) sfToDelete.delete() # Delete frame element relations feRelsToDelete = FeRelations.objects.filter(rel_type="SUBFRAME", parent_frame__name=frame_name, child_frame__name=sf_name) for feRel in feRelsToDelete: feRel.delete() response = HttpResponse() response.status_code = 200 response.content = "Successfully deleted subframe" return response except ValueError as e: response = HttpResponse() response.status_code = 500 response.content = "Encountered error with " + str(e) return response
def create_frame(request): name = request.POST.get('name') # Ensure user enters a valid name if name.replace(' ', '') == '': response = HttpResponse() response.status_code = 400 response.content = "Please enter a valid name" return response frameType = request.POST['frameType'] hasLexicalization = request.POST['hasLexicalization'] try: # Make sure no frame already has this name framesWithName = Frames.objects.filter(name=name) if(len(framesWithName) > 0): response = HttpResponse() response.status_code = 400 response.content = 'Frame with name "' + name + '" already exists' return response Frames.create(name, frameType, hasLexicalization, None, None, None, None) response = HttpResponse() response.content = "Successfully created frame" response.status_code = 200 return response except ValueError as e: response = HttpResponse() response.content = "Encountered error with " + str(e) response.status_code = 500 return response
def handle_exception(self, exc, request): from django.utils.log import getLogger from django.conf import settings logger = getLogger('django.request') exc_info = sys.exc_info() logger.error( 'Internal Server Error: %s', request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) resp = HttpResponse('', status=500, content_type='text/plain') resp.content = '' if hasattr(exc, 'resp_obj'): resp = exc.resp_obj resp.status_code = 500 resp.set_common_headers(request) else: resp = HttpResponse('', status=500, content_type='text/plain') resp.content = 'An error occured.' if settings.DEBUG: from django.views.debug import ExceptionReporter reporter = ExceptionReporter(request, *exc_info) resp.content = reporter.get_traceback_text() resp['Content-Type'] = 'text/plain' return resp
def cert(request): response = HttpResponse() certlist = request.POST.get("certs", None) user = request.user try: if request.GET.get("auth_token"): user = Profile.objects.get(auth_key=request.GET["auth_token"]).user if user.is_anonymous(): response.content = "not logged in!" elif certlist: certlist = json.loads(certlist) for certdata in certlist: if not certdata["ects"]: # Verleihung des BSc-Grads, etc continue certdata["semst"] = Decimal(certdata["semst"]) certdata["ects"] = Decimal(certdata["ects"]) query = dict([(str(k), v) for k, v in certdata.iteritems() if (k in ["lvatype", "lvano"])]) create = dict([(str(k), v) for k, v in certdata.iteritems()]) if not Certificate.objects.filter(user=user, **query): cert = Certificate.create(user=user, **create) response.content = "ok" else: response.content = serializers.serialize("json", Certificate.objects.filter(user=user)) except Exception, e: import traceback response.content = str(e) + "\n" + traceback.format_exc()
def query(request): response = HttpResponse() code = 200 message = {} if request.method == "POST": try: user = request.COOKIES['email']#user = email,在数据表中 req = json.loads(request.body.decode("utf-8")) # print(req) data = models.Question() data.text = req['question'] data.status = 0 data.uploadtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") data.user = user data.save() message["detail"] = "提问成功" code = 200 except Exception as ex: message["detail"] = str(ex) code = 406 response.content = json.dumps(message,ensure_ascii=False) response.status_code = code return response
def obtener_subcategorias_categoria(request, id_categoria): try: response = HttpResponse() if id_categoria == '': raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_CODIGO_CATEGORIA_FALTANTE) else: estado_habilitado = EstadoCategoria.objects.get(nombre=ESTADO_HABILITADO) if Categoria.objects.filter(codigo=id_categoria, estado=estado_habilitado).__len__() < 1: raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_CATEGORIA_HABILITADA_INEXISTENTE) else: categoria = Categoria.objects.get(codigo=id_categoria, estado=estado_habilitado) response.content = armar_response_content(categoria) response.status_code = 200 return response except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, ValueError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, DETALLE_ERROR_SISTEMA)
def answer(request): response = HttpResponse() code = 200 message = {} if request.method == "POST": try: user = request.COOKIES['email'] req = json.loads(request.body.decode("utf-8")) # update user socre curUser = models.User.objects.get(email=user) curUser.score += 1 curUser.balance += 1 curUser.save() # create answer data = models.Answer() data.questionid = req['questionid'] data.text = req['answer'] data.uploadtime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") data.status = 0 data.user = user data.follow = 0 data.save() # update question status question = models.Question.objects.select_for_update().get( questionid=req['questionid']) question.status = 1 question.lastestanswertime = data.uploadtime question.save() message['detail'] = "回答成功" code = 200 except Exception as ex: message['detail'] = str(ex) code = 406 response.content = json.dumps(message, ensure_ascii=False) response.status_code = code return response
def write_csv_output(major_apps): import csv response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=assignment.csv' content = [] content.append(','.join([ 'Application_ID', 'Title', 'FirstName', 'LastName', 'Score', 'Major', 'MajorName', ])) for m, apps in major_apps: cache_apps_score(apps) cache_apps_fields(apps, [PersonalInfo, SubmissionInfo], ['pinfo', 'subinfo']) for a in apps: score = a.score if score == None: score = a.education.anet a.submission_info = a.field_cache['subinfo'] if a.admission_result.is_admitted: major_name = a.admission_result.admitted_major.number else: major_name = '' content.append(u','.join([ a.ticket_number(), a.title, a.first_name, a.last_name, str(score), str(m.number), m.name ])) content.append('') response.content = '\n'.join(content) return response
def mostrar_mecanismos_nuevos(request): response = HttpResponse() datos = obtener_datos_json(request) try: if datos == '': raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") if KEY_ID_FINCA in datos: if datos[KEY_ID_FINCA] == '': raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") finca_actual = Finca.objects.get(idFinca=datos[KEY_ID_FINCA]) mecanismo_riego_finca_list = MecanismoRiegoFinca.objects.filter( finca=finca_actual) tipo_mecanismo_existente_list = [] for mecanismo_riego in mecanismo_riego_finca_list: tipo_mecanismo_existente_list.append( mecanismo_riego.tipoMecanismoRiego) tipo_mecanismo_riego_list = TipoMecanismoRiego.objects.filter( habilitado=True) tipo_mecanismo_riego_nuevo_list = [] for tipo_mecanismo in tipo_mecanismo_riego_list: if tipo_mecanismo_existente_list.__contains__( tipo_mecanismo) == False: tipo_mecanismo_riego_nuevo_list.append(tipo_mecanismo) response.content = armar_response_list_content( tipo_mecanismo_riego_nuevo_list) response.status_code = 200 return response else: raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, TypeError, KeyError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, "Error procesando llamada")
def registrar_categoria(request): try: datos = obtener_datos_json(request) response = HttpResponse() if datos == {}: raise ValueError(ERROR_DATOS_FALTANTES, DETALLE_ERROR_DATOS_INCOMPLETOS) else: if NOMBRE in datos and not (NOMBRE == ''): nombre = lower(datos[NOMBRE]) else: raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_NOMBRE_CATEGORIA_FALTANTE) if DESCRIPCION in datos and not (DESCRIPCION == ''): descripcion = datos[DESCRIPCION] else: descripcion = '' estado_habilitado = EstadoCategoria.objects.get(nombre = ESTADO_HABILITADO) if Categoria.objects.filter(nombre=nombre, estado = estado_habilitado).__len__() >=1: raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_NOMBRE_CATEGORIA_EXISTENTE) else: categoria_creada = Categoria(nombre=nombre, descripcion=descripcion, estado=estado_habilitado) categoria_creada.saveNewCategoria() response.content = armar_response_content(None, CREACION_CATEGORIA) response.status_code = 200 return response except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, ValueError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, DETALLE_ERROR_SISTEMA)
def topbar(request): callback = request.REQUEST.get('callback') user = request.user if not user or user.is_anonymous(): # Ensure that old myguid cookies can be handled correctly guid = request.COOKIES.get('myguid', '').replace('-', '') try: user = User.objects.get(user_guid=guid) except User.DoesNotExist: pass if not user or user.is_anonymous(): user = None ctx = {'user': user} response = HttpResponse(content_type='text/javascript') caller = request.REQUEST.get('site', '') if caller: max_age = 30 * 24 * 60 * 60 last_name = request.REQUEST.get('site_name', caller) response.set_cookie(key='lastmicrosite', value=caller, max_age=max_age, domain='.my.jobs') response.set_cookie(key='lastmicrositename', value=last_name, max_age=max_age, domain='.my.jobs') html = render_to_response('includes/topbar.html', ctx, RequestContext(request)) response.content = "%s(%s)" % (callback, json.dumps(html.content)) return response
def printcontact(request): contact_id = request.GET["id"] eng = request.GET.get("english") if eng == None: eng = "0" contact = Contact.objects.get(id=contact_id) if eng == "1": s = u"用户名称:\t" + unicode(contact.yonghu) + "\n" s += u"仪器型号:\t" + contact.yiqixinghao + "\n" s += u"仪器编号:\t" + contact.yiqibh + "\n" s += u"包箱:\t" + contact.baoxiang + "\n" s += u"审核:\t" + contact.shenhe + "\n" s += u"预计发货时间:\t" + str(contact.yujifahuo_date) + "\n" s += u"合同编号:\t" + contact.hetongbh + "\n" s += u"库存编号\t配件名称\t规格\t数量\t备货\t审核\n" for c in contact.contactitem_set.all(): s += c.item.bh + "\t" + unicode( c.item.name_en) + "\t" + c.item.guige + "\t" + str( c.ct) + c.item.danwei + "\t\t\n" else: s = u"用户名称:\t" + unicode(contact.yonghu) + "\n" s += u"仪器型号:\t" + contact.yiqixinghao + "\n" s += u"仪器编号:\t" + contact.yiqibh + "\n" s += u"包箱:\t" + contact.baoxiang + "\n" s += u"审核:\t" + contact.shenhe + "\n" s += u"预计发货时间:\t" + str(contact.yujifahuo_date) + "\n" s += u"合同编号:\t" + contact.hetongbh + "\n" s += u"sn\tname\t规格\tcount\tpack\t\n" for c in contact.contactitem_set.all(): s += c.item.bh + "\t" + c.item.name + "\t" + c.item.guige + "\t" + str( c.ct) + c.item.danwei + "\t\t\n" r = HttpResponse(content_type="application/x-download") # print dir(r) # print r._headers # r._headers["content-type"]="application/x-download" r.content = s #.encode("gb2312") return r
def serve_static_file(request, file_path=''): """Sends a static file to a user. This serves up the static case files such as the PDFs in a way that can be blocked from search engines if necessary. We do four things: - Look up the document or audio file associated with the filepath - Check if it's blocked - If blocked, we set the x-robots-tag HTTP header - Serve up the file using Apache2's xsendfile """ response = HttpResponse() file_loc = os.path.join(settings.MEDIA_ROOT, file_path.encode('utf-8')) if file_path.startswith('mp3'): item = get_object_or_404(Audio, local_path_mp3=file_path) mimetype = 'audio/mpeg' else: item = get_object_or_404(Document, local_path=file_path) try: mimetype = magic.from_file(file_loc, mime=True) except IOError: raise Http404 if item.blocked: response['X-Robots-Tag'] = 'noindex, noodp, noarchive, noimageindex' if settings.DEVELOPMENT: # X-Sendfile will only confuse you in a dev env. response.content = open(file_loc, 'r').read() else: response['X-Sendfile'] = file_loc file_name = file_path.split('/')[-1] response['Content-Disposition'] = 'attachment; filename="%s"' % \ file_name.encode('utf-8') response['Content-Type'] = mimetype if not is_bot(request): tally_stat('case_page.static_file.served') return response
def login(request): http_response = HttpResponse() issave = request.POST.get('isSave') if request.method == 'POST': username = request.POST.get('username', None) password = request.POST.get('password', None) if username and password: if len(username) > 5: # 读取文件 # search_user(username, password) # login_success = search_user(username, password) login_success = auth.authenticate(username=username, password=password) # if username: if login_success: if issave: http_response.set_cookie('username', username, max_age=10) http_response.set_signed_cookie('password', password, salt='111') # http_response.set_cookie('password', password) info = u'欢迎登录:%s' % username else: info = u'用户名或密码错误' else: info = u'用户名长度不足5位' else: # return HttpResponse(content=u'用户名或密码为空', status = 400) info = u'用户名或密码为空' else: info = u'请求类型无效' http_response.content = info return http_response
def problem_data_file(request, problem, path): object = get_object_or_404(Problem, code=problem) if not request.user.is_superuser and not object.authors.filter( id=request.user.profile.id).exists(): raise Http404() response = HttpResponse() if hasattr(settings, 'PROBLEM_DATA_INTERNAL') and request.META.get( 'SERVER_SOFTWARE', '').startswith('nginx/'): response['X-Accel-Redirect'] = '%s/%s/%s' % ( settings.PROBLEM_DATA_INTERNAL, problem, path) else: try: with problem_data_storage.open(os.path.join(problem, path), 'rb') as f: response.content = f.read() except IOError: raise Http404() type, encoding = mimetypes.guess_type(path) response['Content-Type'] = type or 'application/octet-stream' if encoding is not None: response['Content-Encoding'] = encoding return response
def check_incoming_info(request, guid): """ Chech incoming call info :param request: :param guid: :return: """ try: script = WidgetScript.objects.get(guid=guid) except ObjectDoesNotExist as e: return HttpResponse(status=400) incoming_info = DBService.get_incoming_info(script.guid) response = HttpResponse() response['Access-Control-Allow-Origin'] = '*' if not incoming_info: response.status_code = 204 return response response.status_code = 200 response.content = incoming_info.guid return response
def list_sim_state(request): """Load the Simulation state of all objects, rules, etc.""" message = '' debug = '' status = 'Success' #name = request.POST['name'] simId = int(request.POST['sim_id']) serial = '' response = HttpResponse(); response['Cache-Control'] = 'no-cache, no-store, must-revalidate'; response['Pragma'] = 'no-cache'; response['Expires'] = 0; simlist = [] try: simState = SimulationState.objects.filter(simulation_id=simId) simlist = [obj.name for obj in simState] except SimulationState.DoesNotExist: message = 'No named states have been saved for this simulation.' debug = 'No objects found in simsam_app_simulationstate for simId %d' \ % (simId) except SimulationState.MultipleObjectsReturned: message = 'Multiple objects returned for %d, "%s". ' % (simId, name) debug = 'There is an issue with simsam_app_simulationstate.' status = 'Failed' response.content = json.dumps({ 'status': status, 'message': message, 'debug': debug, 'serialized': serial, 'list': simlist, }) return response
def climax(request): cur_pwd = os.getcwd() if cur_pwd in sys.path: pass else: sys.path.append(cur_pwd+"climax") print(sys.path) if request.method == 'POST': filepath = request.POST.get('filepath',"") if filepath == "": return HttpResponse("参数错误") else: return HttpResponse( get_climax.process_audio(filepath) ) else: response = HttpResponse() response.status_code = 400 response.content = "获取资源方式错误" return response
def obtener_subcategorias(request): try: response = HttpResponse() estado_habilitado = EstadoSubCategoria.objects.get( nombre=ESTADO_HABILITADO) if SubCategoria.objects.filter(estado=estado_habilitado).__len__() < 1: raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_SUBCATEGORIAS_INEXISTENTES) else: subcategorias = SubCategoria.objects.filter( estado=estado_habilitado).order_by('-codigo') response.content = armar_response_list_content(subcategorias) response.status_code = 200 return response except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, ValueError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, DETALLE_ERROR_SISTEMA)
def __call__(self, request): """ Process soap request """ django_response = HttpResponse() def start_response(status, headers): status, _ = status.split(' ', 1) django_response.status_code = int(status) for header, value in headers: django_response[header] = value environ = request.META.copy() body = request.raw_post_data environ['CONTENT_LENGTH'] = len(body) environ['wsgi.input'] = StringIO(body) environ['wsgi.multithread'] = False response = super(DjangoSOAPAdaptor, self).__call__(environ, start_response) django_response.content = "\n".join(response) return django_response
def process(request):#将引擎的实时运行状况反馈到等待页面 if request.method == "POST": fuzzers = ["MEM","DRILLER","TORTOISE"] programName = request.POST.get("programName",None) if not programName : response = HttpResponse() response.content = "没有参数提供" response.status_code = 412 return response else: code_list = codeResult.objects.filter(programName = programName) sourceCodeInstance = code_list[0].code # print(code_list) data_send = {} sum_ms = "" for code in code_list: # codeResultInstance = codeResult.objects.get(id = id) whatsup_individual = pathJoin(MEM_AFL_PATH,"afl-whatsup_individual") whatsup_summary = pathJoin(MEM_AFL_PATH,"afl-whatsup_summary") outs = pathJoin("/root/fuzzResult",code.fuzzer,code.programName) result_individual = invi_table_data(getoutput(whatsup_individual+" "+outs)) if result_individual == -1: response = HttpResponse() response.status_code = 500 return response result_summary = sum_table_data(getoutput(whatsup_summary+" "+outs)) data_send[code.fuzzer] = result_individual data_send[code.fuzzer+"_sum"] = result_summary tempTime = datetime.strptime(code_list[0].time,"%Y-%m-%d %H:%M:%S") + timedelta( minutes=float(sourceCodeInstance.minute),hours=float(sourceCodeInstance.hour)) sum_ms = ( tempTime- datetime.now()).seconds *1000 data_send["sum_ms"] = sum_ms data_send["timeOk"] = tempTime.strftime("%Y-%m-%d %H:%M:%S") # print(data_send) return HttpResponse(json.dumps(data_send), content_type='application/json')
def display_queries(request, stats, queries): """ Generate a HttpResponse of SQL queries for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries. """ sort = request.REQUEST.get('sort_by', 'time') sort_buttons = RadioButtons('sort_by', sort, (('order', 'by order'), ('time', 'time'), ('queries', 'query count'))) output = render_queries(queries, sort) output.reset() output = [html.escape(str(line)) for line in output.readlines()] response = HttpResponse(content_type='text/html; charset=utf-8') response.content = (queries_template % { 'sort_buttons': sort_buttons, 'num_queries': len(queries), 'queries': "".join(output), 'rawqueries': b64encode(pickle.dumps(queries)), 'rawstats': b64encode(pickle_stats(stats)), 'url': request.path }) return response
def challenge(self): """ Returns a 401 response with a small bit on what OAuth is, and where to learn more about it. When this was written, browsers did not understand OAuth authentication on the browser side, and hence the helpful template we render. Maybe some day in the future, browsers will take care of this stuff for us and understand the 401 with the realm we give it. """ response = HttpResponse() response.status_code = 401 realm = 'API' for k, v in self.builder(realm=realm).iteritems(): response[k] = v tmpl = loader.render_to_string('oauth/challenge.html', {'MEDIA_URL': settings.MEDIA_URL}) response.content = tmpl return response
def auth_broker(request): print(request) cookies = request.COOKIES print('cookie: {}'.format(cookies)) response = HttpResponse() response.status_code = 200 if request.method == 'POST': body = json.loads(request.body) username = body['username'] password = body['password'] auth = AuthClient('https://' + OKTA_ORG) res = auth.authn(username, password) print('status={}'.format(res.status_code)) response.status_code = res.status_code content = json.dumps(res.json()) print('response={}'.format(content)) response.content=content return response return response
def _render_doc_to_response(doc_type, doc_content_type, template_name, context_instance=None, debug=None): s = _render_doc(doc_type, template_name, context_instance, debug) if not s[0]: response = None else: if "_" in s[1]: name = s[1].split("_")[1] else: name = s[1] response = HttpResponse() response["Content-Disposition"] = "attachment; filename=%s" % name response[ "Content-Type"] = "application/vnd.oasis.opendocument.spreadsheet" f = open(s[0], "rb") response.content = f.read() f.close() os.remove(s[0]) return response
def handle_request(request): path_info = request.path.replace(reverse('tileserver') + '/', '') layer_id = path_info.split('/')[0] config_dict = get_tileserver_config(layer_id, request=request) config = TileStache.Config.buildConfiguration(config_dict) query_string = "" script_name = "" response = HttpResponse() try: status_code, headers, content = TileStache.requestHandler2( config, path_info, query_string, script_name) response.content = content response.status_code = status_code for header, value in headers.items(): response[header] = value response['Content-length'] = str(len(content)) except Exception as e: print 'No tile data', e, response return response
def challenge(self): """ Returns a 401 response with a small bit on what OAuth is, and where to learn more about it. When this was written, browsers did not understand OAuth authentication on the browser side, and hence the helpful template we render. Maybe some day in the future, browsers will take care of this stuff for us and understand the 401 with the realm we give it. """ response = HttpResponse() response.status_code = 401 for k, v in oauth.build_authenticate_header( realm=self.realm).iteritems(): response[k] = v response.content = """ Unable to authenticate. Make sure you use oAuth 1.0 authentication and a valid consumer key. """ return response
def buscar_sensores_no_asignados(request): response = HttpResponse() datos = obtener_datos_json(request) try: if datos == '': raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") if (KEY_ID_FINCA) in datos: if datos[KEY_ID_FINCA] == '': raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") if Finca.objects.filter( idFinca=datos[KEY_ID_FINCA]).__len__() != 1: raise ValueError(ERROR_FINCA_NO_ENCONTRADA, "No existe la finca ingresada") finca = Finca.objects.get(idFinca=datos[KEY_ID_FINCA]) lista_sensores = Sensor.objects.filter(finca=finca, habilitado=True) lista_sensores_no_asignados = [] for sensor in lista_sensores: if AsignacionSensorComponente.objects.filter( sensor=sensor, fechaBaja__isnull=True).__len__() == 0: lista_sensores_no_asignados.append(sensor) response.content = armar_response_list_content( lista_sensores_no_asignados) response.status_code = 200 return response else: raise ValueError(ERROR_DATOS_FALTANTES, "Datos incompletos") except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, ValueError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, "Error procesando llamada")
def answers(request): response = HttpResponse() code = 200 message = {} if request.method == "POST": try: req = json.loads(request.body.decode("utf-8")) questionid = req["questionid"] # print(req) data = models.Answer.objects.select_for_update().filter(questionid = questionid).order_by('-uploadtime') answers = [] for d in data: if d.status != -1: answer = {} answer["answer"] = d.text answer["answerid"] = d.answerid answers.append(answer) message["answers"] = answers except Exception as ex: message['detail'] = str(ex) code = 406 response.content = json.dumps(message,ensure_ascii=False) response.status_code = code return response
def obtener_pregunta_id(request, id_pregunta): try: response = HttpResponse() if id_pregunta == '': raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_PREGUNTA_FALTANTE) else: if Pregunta.objects.get(id=id_pregunta): pregunta = Pregunta.objects.get(id=id_pregunta) response.content = armar_response_content(pregunta) response.status_code = 200 return response else: raise ValueError(ERROR_DATOS_INCORRECTOS, DETALLE_ERROR_PREGUNTA_INEXISTENTE) except ValueError as err: print err.args return build_bad_request_error(response, err.args[0], err.args[1]) except (IntegrityError, ValueError) as err: print err.args response.status_code = 401 return build_bad_request_error(response, ERROR_DE_SISTEMA, DETALLE_ERROR_SISTEMA)
def update_stk_taskhandler(request): ''' start chain update task since last update date ''' fname = '{} {}'.format(__name__,'update_stk_taskhandler') response = HttpResponse(fname) response.status_code = httplib.OK t_stk_no = request.GET['stk_no'] logging.info('{}: with stock {}'.format(fname,t_stk_no)) t_stk_type = StockModel.get_type_by_stk_no(t_stk_no) if t_stk_type == StockModel.MARKET_TYPE_TWSE: t_last_ym = TWSEStockModel.get_stk_update_ym(t_stk_no) elif t_stk_type == StockModel.MARKET_TYPE_OTC: t_last_ym = OTCStockModel.get_stk_update_ym(t_stk_no) else: response.content = 'stk_no {} ERROR'.format(t_stk_no) logging.warning('{}: stk_no {} ERROR'.format(fname,t_stk_no)) return response #-> start chain update task if t_last_ym == date.today().strftime('%Y%m'): logging.info('{}: stock {} already updted, task skipped'.format(fname,t_stk_no)) else: taskqueue.add(method = 'GET', url = os.path.dirname(os.path.dirname(request.get_full_path())) + "/stk_cupdate/" , countdown = datetime.now().second % 5, params = { 'stk_no': t_stk_no, 'year_month': t_last_ym, 'type': 'all', }) response.status_code = httplib.OK return response
def insert_comment(request): if request.method == 'POST': xhr_dict = parse_requeset_body(request.body.decode()) ip_record = models.Ips.objects.get(ip=xhr_dict['ip']) comment_record = models.Comment.objects.filter(ip=xhr_dict['ip']) if comment_record: comment_record[0].comment = xhr_dict['comment'] comment_record[0].save() logger.info("<DB exec> Comment has been updated.") else: new_record = models.Comment.objects.create() new_record.ip = xhr_dict['ip'] new_record.comment = xhr_dict['comment'] new_record.save() logger.info("<DB exec> Comment inserted successfully.") ip_record.comment = xhr_dict['comment'] ip_record.save() logger.info("<Set> %s 备注设置成功!" % xhr_dict['ip']) return HttpResponse("设置成功!") else: r = HttpResponse() error_dict = {'message': 'error', 'state': '404'} r.content = json.dumps(error_dict) return r
def favorite(request): if request.method == 'PUT': #tokens= Token.objects.all req_body = json.loads(request.body) if 'access_token' not in req_body: resp = HttpResponse(content_type='application/json', status=400) resp.content = json.dumps({"error": "access_token is required"}) return resp if 'reddit_id' not in req_body: resp = HttpResponse(content_type='application/json', status=400) resp.content = json.dumps({"error": "reddit_id is required"}) return resp token = Token.objects.filter(key=req_body.get("access_token")) if not token: resp = HttpResponse(content_type='application/json', status=400) resp.content = json.dumps({"error": "invalid access_token"}) return resp print(token) reddit_id = req_body.get("reddit_id") article_tags = req_body.get("tags") if token and reddit_id: favorite = models.Favorite() favorite.user_id = token[0].user_id favorite.reddit_id = reddit_id favorite.save() if article_tags: for tag in article_tags: t = models.Tags() t.tag = tag t.favorite_id = favorite.id t.save() resp = HttpResponse(content_type='application/json') resp.content = json.dumps( {"msg": "Article successfully favorited and tagged"}) else: resp = HttpResponse(content_type='application/json', status=401) resp.content = json.dumps({"error": "invalid token or reddit_id"}) return resp else: resp = HttpResponse(content_type='application/json', status=405) resp.content = json.dumps({"error": "send a PUT request"}) return resp
def chat(request): response = HttpResponse(content_type='application/json') response["Access-Control-Allow-Origin"] = "*" if request.method == 'POST': input = None try: input = json.loads(request.body) except: response.content = json.dumps({'error': 'Not valid JSON'}) return response if not isinstance(input, dict): response.content = json.dumps( {'error': 'JSON should be an object'}) elif 'nickname' not in input: response.content = json.dumps( {'error': 'JSON object should have "nickname" property'}) elif 'message' not in input: response.content = json.dumps( {'error': 'JSON object should have "message" property'}) else: c = ChatMessage() c.nickname = str(input['nickname']) c.message = str(input['message']) c.save() response.content = json.dumps({'result': 'ok'}) else: def message_to_dict(m): return { 'nickname': m.nickname, 'message': m.message, 'time': int(time.mktime(m.time.utctimetuple())) } messages = ChatMessage.objects.all().order_by('-time')[0:15] messages = map(message_to_dict, messages) response.content = json.dumps(messages) return response