def readme(request): try: # Account guest_account = get_guestuser() if guest_account: data = {'text': '', 'account': guest_account} else: logger.message( 'guest accounts is not found. Please check database settings...' ) return server_error(request) # markdown path path = os.path.join(os.path.dirname(__file__), '..', 'README.md') logger.debug('path=%s' % path) with open(path, mode='r') as mdfile: # Read text content = mdfile.read() data['text'] = content return render(request, 'home/readme.html', context=data) except Exception as e: logger.warning(e.message, trace=True) return server_error(request)
def search_more(request): """ Handle AJAX requests for infinite scrolling on the movie search page. """ search_term = request.GET['q'] if 'p' in request.GET: page = int(request.GET['p']) else: page = 1 logger.info('Loading Search Page %s. Term: %s', page, search_term) # Get movies for search term try: movies = Movie.search(search_term, page)['items'] except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') except QueryException: return server_error(request, 'errors/query_error.html') except InvalidSearchException: return server_error(request, 'errors/query_error.html') # Convert to a dictionary, because that's the most easily serializable to JSON movies_dict = [{ 'id': a.m_id, 'title': a.title, 'overview': a.overview, 'poster_path': a.poster_path } for a in movies] return HttpResponse(json.dumps(movies_dict), content_type="application/json")
def post_new_thread(request): if request.user.is_authenticated() and request.POST: member = Member.objects.get(user=request.user) category_slug = request.POST.get("category_slug", -1) thread_title = request.POST.get("thread_title", -1) content = request.POST.get("content", -1) log.error(category_slug + " " + thread_title + " " + content) if category_slug != -1 or thread_title != -1 or content != -1: category = Category.objects.get(slug=category_slug) thread = Thread() thread.category = category thread.op = member thread.title = thread_title thread.save() thread_slug = thread.slug post = Post() post.author = member post.thread = thread post.content = content post.save() return HttpResponse("category/" + category_slug + "/thread/" + thread_slug) else: return server_error(request) else: return server_error(request)
def detail(request, movie_id): """ Gathers info and data on the movie specified by movie_id. Displays it with the movie detail html. """ try: logger.info('Attempting to retrieve details for movie with id %s' % movie_id) movie = Movie.get_details(movie_id) except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') logger.info('Loading Movie Detail Page. Movie: %s', movie) profile = Profile.get(request.user) user_rating = 0 lists = [] if profile: user_rating = Rating.get_rating_for_user(profile, movie) lists = UserList.objects.filter(user=profile) for user_list in lists: user_list.list_items = UserListItem.objects.filter(user_list=user_list) return render(request, 'movie/detail.html', { 'movie': movie, 'review_list': get_review_approvals(request, Review.objects.filter(movie=movie).filter(deleted=False)), 'display_title': False, # To display titles of movie next to Review 'already_reviewed': already_reviewed(movie, profile), 'user_rating': user_rating, 'lists': lists })
def browse_more(request): """ Handle AJAX requests for infinite scrolling on the browse movie page. """ if 'p' in request.GET: page = int(request.GET['p']) else: page = 1 logger.info('Loading browse page %s...' % page) # Get movies for genre. If no genre is passed in, a general list of movies # will be shown. if 'genre' in request.GET and request.GET['genre']: genre_id = int(request.GET['genre']) try: movies = Movie.get_movies_for_genre(genre_id, page)['items'] except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') else: page_start = page * 20 - 19 page_end = page * 20 # No try-except required because no api query movies = Movie.get_popular(1)['items'][page_start:page_end] # Convert to a dictionary, because that's the most easily serializable to JSON movies_dict = [{ 'id': a.m_id, 'title': a.title, 'overview': a.overview, 'poster_path': a.poster_path } for a in movies] return HttpResponse(json.dumps(movies_dict), content_type="application/json")
def get_all_events(request): response = HttpResponse(content_type='text/csv') response['content-Disposition'] = 'attachment; filename="all_events.csv"' writer = csv.writer(response) server_error(request) # these could blow up, but that'll just return a 500, which is good for now sr = ScraperRunner() writer.writerows(sr.scrape_events()) return response
def add_category(request): if request.user.is_authenticated() and request.POST: member = Member.objects.get(user=request.user) if member and member.type == 2: category = Category() category.name = request.POST["category"] category.save() return redirect("/") else: return server_error(request) else: return server_error(request)
def save_edited_post(request, slug_cat, slug_thread, post_number): if request.user.is_authenticated() and request.POST: post = Post.objects.get(pk=post_number) member = Member.objects.get(user=request.user) if post and member and (member.type > 0 or post.author == member): post.content = request.POST["content"] post.save() return HttpResponse("category/" + slug_cat + "/thread/" + slug_thread + "?page=1") else: return server_error(request) else: return server_error(request)
def check(request, course_id, lesson_id): course = models.Course.objects.get(pk=course_id) lesson = models.Lesson.objects.get(pk=lesson_id) qa = list(models.Question.objects.filter(lesson=lesson).all()) if len(qa) == 0: return server_error(request) if request.method == 'POST': qa = request.session['qa'] question_index = request.session['question_index'] + 1 if question_index <= len(qa): request.session['question_index'] = question_index title = F'Question {question_index} out of {len(qa)}. {qa[question_index-1]["question_text"]}' return JsonResponse({ 'result': 'ok', 'question': title, 'last': False }) else: title = F'Well done! You have finished the lesson with score {request.session["score"]}' return JsonResponse({ 'result': 'ok', 'question': title, 'last': True }) if len(qa) == 0: return server_error(request) random.shuffle(qa) request.session['qa'] = [{ 'question_text': i.question_text, 'answer_text': i.answer_text, 'id': i.id } for i in qa] request.session['question_index'] = 1 request.session['score'] = 0 qa_pair = qa[0] questions_count = len(qa) return render( request, 'yourvocab/check.html', { 'course': course, 'lesson': lesson, 'question_index': 1, 'questions_count': questions_count, 'qa': qa_pair })
def rate(request, movie_id): try: movie = Movie.get_details(movie_id) except APIException: logger.exception('Failed to submit rating for movie') return server_error(request, 'errors/api_error.html') except AccessException: logger.exception('Failed to submit rating for movie') return server_error(request, 'errors/access_error.html') stars = request.GET['stars'] user = Profile.get(request.user) logger.debug('Rating. User: %s. Movie: %s. Stars: %s', user.user.username, movie.m_id, stars) Rating.set_rating_for_user(movie, stars, user) return HttpResponseRedirect('/movie/detail/%s' % movie_id)
def register_user(request): context_dict = {} if request.method == "POST": check_user = User.objects.filter(username=request.POST["username"], email=request.POST["email"]) if check_user: context_dict["error"] = "User Already Exists!" return render(request, "register.html", context_dict) else: user = User.objects.create_user( username=request.POST["username"], email=request.POST["email"], password=request.POST["password"] ) user.is_active = False user.last_name = request.POST["last_name"] user.first_name = request.POST["first_name"] user.save() member = Member() member.user = user member.date_of_birth = datetime.strptime(request.POST["dob"], "%d/%m/%y") member.details_visible = "visible" in request.POST member.bio = request.POST["bio"] member.location = request.POST["location"] member.save() send_verification_email(request, user) request.session["status"] = "Registration Successful.Verification link sent to your email address" redirect_to = "/" if "next" not in request.POST else request.POST["next"] return redirect("/login?next=" + redirect_to) elif request.method == "GET": if "next" in request.GET: context_dict["next"] = request.GET["next"] return render(request, "register.html", context_dict) else: return server_error(request)
def login_user(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: member = Member.objects.get(user=user) if user.is_active and not member.banned: login(request, user) redir = "/" if "next" not in request.POST else request.POST["next"] return redirect(redir) elif not user.is_active: return render( request, "login.html", { "error": "Account not activated,check email", "resend_email_form": True, "user_username": user.username, }, ) else: return render(request, "login.html", {"error": "You account has been banned!,Contact Admin"}) else: return render(request, "login.html", {"error": "Invalid Username or Password"}) elif request.method == "GET": context_dict = {"next": "/"} if "status" in request.session: context_dict["status"] = request.session["status"] del request.session["status"] if "next" in request.GET: context_dict["next"] = request.GET["next"] return render(request, "login.html", context_dict) else: return server_error(request)
def delete_post(request, slug_cat, slug_thread, post_number): if request.user.is_authenticated(): post = Post.objects.get(pk=post_number) member = Member.objects.get(user=request.user) if post and member and (member.type > 0 or post.author == member): thread = Thread.objects.get(slug=slug_thread) if thread and thread.category.slug == slug_cat: post.visible = False post.save() return redirect("/category/" + slug_cat + "/thread/" + slug_thread + "?page=" + 1) else: return server_error(request) else: return server_error(request) else: return redirect("/login/")
def darResponse(request, seq_id): seq_id = seq_id.encode('ascii', 'ignore') if request.method == 'GET': logger.info("Request to retrieve DAR from" + \ `request.META['REMOTE_ADDR']` +\ ", id="+`seq_id`) dar = dmcontroller.get_next_dar(seq_id) if None == dar: logger.error("No dar!") server_error(request) else: return HttpResponse(dar, content_type="application/xml") else: logger.error("Unxexpected POST request on darResponse url,\n" + \ `request.META['SERVER_PORT']`) raise Http404
def home(request): """Renders the home page with all categories. Categories are sorted by number of posts under them in descending order. Most recently active two threads are shown under each category. :param request: Request object :return: rendered page """ context_dict = {} categories = [] general_category = Category.objects.get_or_create(name="General Discussion")[0] if general_category: categories_qs = ( Category.objects.exclude(slug="general-discussion") .annotate(num_threads=Count("thread")) .order_by("-num_threads") ) top_threads = {} for category in chain([general_category], categories_qs): categories.append(category) top_threads[str(category.pk)] = [ [thread, str(thread.post_set.count() - 1)] for thread in Thread.objects.filter(category=category, visible=True).order_by("-last_modified")[:2] ] context_dict["categories"] = categories context_dict["top_threads"] = top_threads if request.user.is_authenticated(): member = Member.objects.get(user=request.user) if member: context_dict["member"] = member return render(request, "home.html", context_dict) else: return server_error(request)
def add(request, user_id): try: template = 'system_app/cube/add.html' context_dict = dict() # Get user object user = User.objects.get(id=user_id) context_dict['merchant'] = user if request.method == "POST": form = CubeForm(request.POST) context_dict['form'] = form if form.is_valid(): cube = form.save(commit=False) cube.user = user cube.save() messages.success(request, 'Successfully added cube.') return redirect('/system/cube/{0}'.format(cube.id)) else: form = CubeForm() context_dict['form'] = form except ObjectDoesNotExist: raise Http404 except: return server_error(request) return render(request, template, context_dict)
def api_server_error(request, *args, **kwargs): if settings.DEBUG is False and request.META.get( 'CONTENT_TYPE', None) == "application/json": return HttpResponse(json.dumps( {"error": _("Server application error")}), status=status.HTTP_500_INTERNAL_SERVER_ERROR) return server_error(request, *args, **kwargs)
def inventory(request, cube_id): try: if request.method == "POST": for item in request.POST: # format: __<item.id>_<item.code>_<type>' e.g.'__1_A1-0001_out' if item.startswith('__'): splits = item.split('_') target_item = Item.objects.get(id=int(splits[2]), code=splits[3]) # print('{0} => {1}'.format(item, request.POST.get(item))) if splits[-1] == 'in': val = int(request.POST.get(item)) target_item.quantity = target_item.quantity + val elif splits[-1] == 'out': val = int(request.POST.get(item)) target_item.quantity = target_item.quantity - val elif splits[-1] == 'price': val = float(request.POST.get(item)) target_item.price = val target_item.save() messages.success(request, 'Successfully updates inventory.') return redirect('/system/cube/{0}#cube-item'.format(cube_id)) except ObjectDoesNotExist: raise Http404() except: raise return server_error(request) return render(request, template, context_dict)
def add(request, cube_id): try: template = 'system_app/item/add.html' context_dict = dict() # Get cube object cube = Cube.objects.get(id=cube_id) context_dict['cube'] = cube if request.method == "POST": form = ItemForm(request.POST) context_dict['form'] = form if form.is_valid(): item = form.save(commit=False) item.cube = cube item.save() messages.success(request, 'Successfully added item.') return redirect('/system/item/{0}'.format(item.id)) else: form = ItemForm() context_dict['form'] = form except ObjectDoesNotExist: raise Http404 except: raise return server_error(request) return render(request, template, context_dict)
def pay(request, payout_id): try: template = 'system_app/sales/pay.html' context_dict = dict() # Get user object payout = Payout.objects.get(id=payout_id) context_dict['payout'] = payout sales = Sales.objects.filter(payout=None).order_by('-date') context_dict['sales'] = sales if request.method == "POST": selected_sales = request.POST.getlist('sales') for sale_id in selected_sales: selected_sale = Sales.objects.get(id=int(sale_id)) selected_sale.payout = payout.id selected_sale.save() return redirect('/system/payout/{0}'.format(payout.id)) except: # raise return server_error(request) return render(request, template, context_dict)
def handle_uncaught_exception(self, request, exc_info): """ Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an error. And of course it is overriden, to get rid of resolver ;) """ from django.conf import settings if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise logger.error('Internal Server Error: %s', request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *exc_info) from django.views import defaults return defaults.server_error(request)
def handler500(request): """ Custom 500 view :param request: :return: """ return server_error(request, template_name='base/500.html')
def error500(request): if request.headers.get('Accept') == 'application/json': response_data = {} response_data['detail'] = 'Internal server error.' return HttpResponseNotFound(json.dumps(response_data), content_type="application/json") return defaults.server_error(request)
def error500(request): if request.headers.get("Accept") == "application/json": response_data = {} response_data["detail"] = "Internal server error." return HttpResponseNotFound(json.dumps(response_data), content_type="application/json") return defaults.server_error(request)
def process_exception(self, request, exception): if settings.DEBUG: return template_name = '500_ajax.html' if request.is_ajax else "500.html" return server_error(request, template_name=template_name, exception=exception)
def change_password(request): try: template = 'viewer_app/password.html' context_dict = dict() if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) context_dict['form'] = form if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('/thecubestore/profile') else: form = PasswordChangeForm(request.user) context_dict['form'] = form except: return server_error(request) return render(request, template, context_dict)
def _func(request, *args, **kwargs): if request.method != method: log.warning('wrong_method|url=%s,method=%s', request.get_full_path().encode('utf-8'), request.method) return api_response(Result.ERROR_PARAMS) if isinstance(form, (Draft4Validator)): try: formdata = json.loads(request.body) except: if request.body: log.warning('params_error|format=json,url=%s,body=%s', request.get_full_path().encode('utf-8'), request.body) return api_response(Result.ERROR_PARAMS) try: form.validate(formdata) data = formdata except Exception as ex: log.warning( 'params_error|format=form,url=%s,error=%s,body=%s', request.get_full_path().encode('utf-8'), ex, formdata) return api_response(Result.ERROR_PARAMS) return func(request, data, *args, **kwargs) return defaults.server_error(request)
def add(request): try: template = 'system_app/announcement/add.html' context_dict = dict() if request.method == "POST": form = AnnouncementForm(request.POST) context_dict['form'] = form if form.is_valid(): announcement = form.save(commit=False) announcement.save() messages.success(request, 'Successfully added announcement.') return redirect('/system/announcement/{0}'.format( announcement.id)) else: form = AnnouncementForm() context_dict['form'] = form except ObjectDoesNotExist: raise Http404 except: return server_error(request) return render(request, template, context_dict)
def view_500(request): if not request.path.startswith('/' + ASKBOT_URL): template_name = 'errors/500.html' else: template_name = '500.html' return server_error(request, template_name=template_name)
def forge_3legged_redirect(request): # DEBUG http.dump_request(request) # Check session if 'access-token' in request.session: logger.message('session[access-token]=%s' % request.session['access-token']) if request.session['access-token']: # Because it has already access token, turn back to request page return redirect(request.META['HTTP_REFERER']) else: logger.message('session[access-token] is empty') try: callback = OAUTH_CALLBACK_URL #callback = OAUTH_CALLBACK_URL + '/' + request.session['_auth_user_hash'] requesturl = forgeOA.generate_3l_code_url(callback_url=callback) logger.message(requesturl) response = HttpResponse(requesturl, content_type='text/plain') return response except Exception as e: logger.warning(e.message, trace=True) return server_error(request)
def user_login(request): try: # Redirection template = 'system_app/login.html' redirect = request.GET.get('next', '/system/dashboard') context_dict = dict() context_dict['redirect_to'] = redirect if not request.user.is_anonymous() and not is_crew(request.user): messages.error(request, NOT_CREW.format(request.user)) if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(redirect) else: messages.error(request, INACTIVE_USER) return render(request, template) else: messages.error(request, INVALID_CREDENTIALS) return render(request, template, context_dict) except Exception as e: return server_error(request) return render(request, template, context_dict)
def server_error(request, template_name='500.html'): """ Custom 500 error handler. The exception clause is so broad to capture any 500 errors that may have been generated from getting the response page e.g. if the database was down. If they were not handled they would cause a 500 themselves and form an infinite loop. If no ResponsePage exists for with type ``RESPONSE_HTTP500`` then the default template render view will be used. Templates: :template:`500.html` Context: page A ResponsePage with type ``RESPONSE_HTTP500`` if it exists. """ try: rendered_page = get_response_page(request, http.HttpResponseServerError, 'icekit/response_pages/500.html', abstract_models.RESPONSE_HTTP500) if rendered_page is not None: return rendered_page except Exception: pass return defaults.server_error(request, template_name)
def handler500(request, template_name='500.html'): """ Overrides the default Django implementation of a 500 error so that a JSon response will be provided if the accept header of the request has a value of "application/json". Otherwise the default server error implementation is called. To enable this handler, the DEBUG setting in the Django settings must be set to False :param request: Current Request :type request: WSGIRequest :param template_name: Template of the error page :type template_name: str :return: Response :rtype: object """ if request is not None and 'application/json' in request.META.get( 'HTTP_ACCEPT', ''): logger.error("Unhandled exception!") j_send = JSend() j_send.status = JSend.Status.error j_send.code = status.HTTP_500_INTERNAL_SERVER_ERROR j_send.message = 'Unexpected API Server Error' j_send_serializer = JSendSerializer(data=j_send.__dict__) j_send_serializer.is_valid(True) return JsonResponse(j_send_serializer.data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return server_error(request=request, template_name=template_name)
def edit(request, store_id): try: template = 'system_app/store/edit.html' context_dict = dict() instance = Store.objects.get(id=store_id) if request.method == "POST": form = StoreForm(request.POST, instance=instance) context_dict['form'] = form if form.is_valid(): store = form.save(commit=False) store.save() messages.success(request, 'Successfully edited store.') return redirect('/system/merchant/{0}'.format(store.user.id)) else: form = StoreForm(instance=instance) context_dict['form'] = form except ObjectDoesNotExist: raise Http404 except: return server_error(request) return render(request, template, context_dict)
def edit(request, payout_id): try: template = 'system_app/payout/edit.html' context_dict = dict() instance = Payout.objects.get(id=payout_id) if request.method == "POST": form = PayoutForm(request.POST, instance=instance) context_dict['form'] = form if form.is_valid(): payout = form.save(commit=False) payout.save() messages.success(request, 'Successfully edited payout.') return redirect('/system/payout/{0}'.format(payout.id)) else: form = PayoutForm(instance=instance) context_dict['form'] = form except ObjectDoesNotExist: raise Http404 except: return server_error(request) return render(request, template, context_dict)
def dispatcher(request, app, view_name, params): params = params.split('/')[0:-1] full_app_name = settings.APP_MAPPING.get(app, app) fromlist = full_app_name.split('.') try: views = __import__('{}.views'.format(full_app_name), fromlist=list(map(str, fromlist))) func = getattr(views, view_name) except ComponentHasResponseException as e: raise e except (ImportError, TypeError, AttributeError) as e: traceback.print_exc() return page_not_found(request, e, 'error404.html') try: return func(request, *params) except ComponentHasResponseException as e: raise e except Exception as e: print(e) traceback.print_exc() return server_error(request, 'error500.html')
def server_error(request): """ Custom 500 error handler. """ if request.path.startswith('/api/'): return HttpResponseServerError('Server Error', content_type='application/json') return defaults.server_error(request)
def handler500(request): if conf.MAINTENANCE_MODE or not (Release.is_up_to_date()): context = {'request': request} return render_to_response('maintenance.html', context, status=conf.MAINTENANCE_STATUS_CODE) return server_error(request)
def difficulties_view(request): try: conn = redis.Redis(port=6380) conn.ping() except RedisError: try: conn = redis.Redis() conn.ping() except RedisError: return server_error(request) if request.method == 'POST': form = DifficultyForm(conn, request.POST) if form.is_valid(): diff = form.cleaned_data['difficulty'] tasks = [] for url in conn.smembers(diff): dct = conn.hgetall(url) task = { 'url': url, 'name': dct[b'name'].decode('utf-8'), } tasks.append(task) headers = ['Link to problem', 'Name'] return render(request, 'tags.html', { 'form': form, 'tasks': tasks, 'headers': headers }) else: form = DifficultyForm(conn) return render(request, 'tags.html', {'form':form})
def wrapper(request, *args, **kwargs): try: return f(request, *args, **kwargs) except Exception as e: if 'matches the given query' in (str(e)): raise Http404() logger.info(str(e)) return server_error(request, template_name='500.html')
def _initialize_for_request(self, request): self.request = request try: self.applicant = self.request.user.applicantprofile if self.applicant.must_change_password: # TODO: forced password change return server_error(self.request) except ObjectDoesNotExist: # TODO: make a landing page for non-applicant users return server_error(self.request) try: self.application = self.applicant.current_application if self.application.submitted: return redirect(self._uri_of('submitted')) except ObjectDoesNotExist: # TODO: same landing page as for non-applicant users return server_error(self.request) self.issues = CustomValidationIssueSet() self.application.custom_validate(self.issues) self._my_pages = [] self._page_index = None needs_finaid = Award.objects.check_app_needs_finaid(self.application) needs_essay = Award.objects.check_app_needs_essay(self.application) for index, names in enumerate(WizardPageView.PAGES): short_name, long_name = names if ((not needs_finaid and short_name == 'finaid') or (not needs_essay and short_name == 'essay')): if type(self).page_name == short_name: return redirect(self._uri_of(self._my_pages[-1][0])) else: continue if type(self).page_name == short_name: self._page_index = index self._my_pages.append((short_name, long_name)) if self._page_index == None: raise KeyError('invalid page name: {}'.format(page_name)) failing_sentry = self._find_failing_sentry(including_me=False) if failing_sentry is not None: add_message(self.request, ERROR, 'Please complete this section first') return redirect(self._uri_of(failing_sentry.page_name))
def darResponse(request,seq_id): seq_id = seq_id.encode('ascii','ignore') if request.method == 'GET': logger.info("Request to retrieve DAR from" + \ `request.META['REMOTE_ADDR']` +\ ", id="+`seq_id`) dar = dmcontroller.get_next_dar(seq_id) if None == dar: logger.error("No dar!") server_error(request) else: return HttpResponse( dar, content_type="application/xml") else: logger.error("Unxexpected POST request on darResponse url,\n" + \ `request.META['SERVER_PORT']`) raise Http404
def edit_post(request, slug_cat, slug_thread, post_number): if request.user.is_authenticated(): post = Post.objects.get(pk=post_number) member = Member.objects.get(user=request.user) if post and member and (member.type > 0 or post.author == member): thread = Thread.objects.get(slug=slug_thread) if thread and thread.category.slug == slug_cat: return render( request, "editpost.html", {"post": post, "member": post.author, "category_slug": slug_cat, "thread_slug": slug_thread}, ) else: return server_error(request) else: return server_error(request) else: return redirect("/login/")
def test_custom_templates_wrong(self): """ Default error views should raise TemplateDoesNotExist when passed a template that doesn't exist. """ rf = RequestFactory() request = rf.get('/') with self.assertRaises(TemplateDoesNotExist): bad_request(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): permission_denied(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): page_not_found(request, Http404(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): server_error(request, template_name='nonexistent')
def jsonable_server_error(request, template_name='500.html'): """ 500 error handler that serves JSON on an AJAX request, and proxies to the Django default `server_error` view otherwise. """ if request.is_ajax(): msg = {"error": "The edX servers encountered an error"} return HttpResponseServerError(json.dumps(msg)) else: return server_error(request, template_name=template_name)
def changeemail(request): """ changeemail view. It require password or openid to allow change. url: /email/* template : authopenid/changeemail.html """ msg = request.GET.get('msg', '') extension_args = {} user_ = request.user redirect_to = get_url_host(request) + reverse('user_changeemail') action = 'change' if request.POST: form = ChangeemailForm(request.POST, user=user_) if form.is_valid(): if not form.test_openid: new_email = form.cleaned_data['email'] if new_email != user_.email: if settings.EMAIL_VALIDATION == 'on': action = 'validate' else: action = 'done_novalidate' set_new_email(user_, new_email,nomessage=True) else: action = 'keep' else: #what does this branch do? return server_error('') request.session['new_email'] = form.cleaned_data['email'] return ask_openid(request, form.cleaned_data['password'], redirect_to, on_failure=emailopenid_failure) elif not request.POST and 'openid.mode' in request.GET: return complete(request, emailopenid_success, emailopenid_failure, redirect_to) else: form = ChangeemailForm(initial={'email': user_.email}, user=user_) output = render('authopenid/changeemail.html', { 'form': form, 'email': user_.email, 'action_type': action, 'msg': msg }, context_instance=RequestContext(request)) if action == 'validate': set_email_validation_message(user_) return output
def make_post(request): """Responds to AJAX request for posting a reply to a thread. :param request: Request object :return: HttpResponse 200 or 500 """ if request.user.is_authenticated() and request.POST: member = Member.objects.get(user=request.user) thread_id = request.POST.get("thread_id", -1) content = request.POST.get("content", -1) if thread_id != -1 and content != -1 and member: post = Post() post.author = member post.thread = Thread.objects.get(pk=thread_id) post.content = content post.save() return HttpResponse(200) else: return server_error(request) else: return server_error(request)
def verify_user(request): if request.method == "GET": if "user" in request.GET and "hash" in request.GET: user = User.objects.get(username=request.GET["user"]) if request.GET["hash"] == hashlib.md5(user.password.encode("utf-8")).hexdigest(): user.is_active = True user.save() request.session["status"] = "Account Verified!" return redirect("/login/") else: return redirect("/") elif request.method == "POST": user = User.objects.get(username=request.POST["user_username"]) if user is not None: send_verification_email(request, user) request.session["status"] = "Verification link sent!" return redirect("/login/") else: return server_error(request) else: return server_error(request)
def browse(request): logger.info('Loading Browse Page') global __cached_filters if __cached_filters is None: # Retrieve list of filters available to the user try: browse_filters = get_browse_filters() except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') __cached_filters = browse_filters else: logger.info('Using Cached Browse Filters') browse_filters = __cached_filters # Performs the filtering. Currently only implemented for genres if 'genre' in request.GET and request.GET['genre']: # If request contains a genre id to filter, retrieve movies of that # genre from the API genre_id = int(request.GET['genre']) try: movies = Movie.get_movies_for_genre(genre_id, 1)['items'] except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') else: # If no genre selected, show first page (page size 20) of popular movies movies = Movie.get_popular(1)['items'][:20] # No error genre_id = '' logger.info('Rendering Browse Page') return render(request, 'movie/browse.html', { 'browse_filters': browse_filters, 'results_list': movies, 'genre': genre_id })
def handler_http_500(request, template_name='500.html'): """HTTP 500 error handler that understands Aceept header""" # FIXME: Figure out how to do mimetype dispatching better accepts = request.META.get('HTTP_ACCEPT', 'text/html') if 'application/json' in accepts: return JsonResponse( status=500, content_type='application/json', data={'error': 'server error'} ) if 'text/html' in accepts: return server_error(request, template_name=template_name)
def search(request): """ Search for movies by keyword. Returns the search page html. """ search_term = request.GET['q'] page = 1 logger.info('Loading Search Page %s. Term: %s', page, search_term) try: movies = Movie.search(search_term, page) except APIException: return server_error(request, 'errors/api_error.html') except AccessException: return server_error(request, 'errors/access_error.html') except QueryException: return server_error(request, 'errors/query_error.html') except InvalidSearchException: return server_error(request, 'errors/query_error.html') return render(request, 'movie/search.html', { 'movie_results': movies, 'user_results': Profile.search(search_term), 'search_term': search_term, })
def process_request(self, request): """ Check for denied Hosts. """ try: # Attempt to obtain Host: from http header. This may elicit a # SuspiciousOperation if Host: doesn't match ALLOWED_HOSTS. # Unceremoniously squash these errors to prevent log emails, # diverting straight to 500 page. request.get_host() except SuspiciousOperation: return server_error(request)
def changeemail(request): """ changeemail view. It require password or openid to allow change. url: /email/* template : authopenid/changeemail.html """ msg = request.GET.get("msg", "") extension_args = {} user_ = request.user redirect_to = get_url_host(request) + reverse("user_changeemail") action = "change" if request.POST: form = ChangeemailForm(request.POST, user=user_) if form.is_valid(): if not form.test_openid: new_email = form.cleaned_data["email"] if new_email != user_.email: if settings.EMAIL_VALIDATION == "on": action = "validate" else: action = "done_novalidate" set_new_email(user_, new_email, nomessage=True) else: action = "keep" else: # what does this branch do? return server_error("") request.session["new_email"] = form.cleaned_data["email"] return ask_openid(request, form.cleaned_data["password"], redirect_to, on_failure=emailopenid_failure) elif not request.POST and "openid.mode" in request.GET: return complete(request, emailopenid_success, emailopenid_failure, redirect_to) else: form = ChangeemailForm(initial={"email": user_.email}, user=user_) output = render( "authopenid/changeemail.html", {"form": form, "email": user_.email, "action_type": action, "msg": msg}, context_instance=RequestContext(request), ) if action == "validate": set_email_validation_message(user_) return output
def server_error(request, template_name = '500.html'): """ Mobile 500 error handler. Templates: `500.html` Context: None """ user_agent = utils.get_user_agent(request) if user_agent: template_list = ( 'mobility/%s/500.html' % user_agent, template_name, ) return HttpResponseServerError(loader.render_to_string(template_list)) return defaults.server_error(request, template_name)
def start_new_thread(request): context_dict = {} context_dict["selected_category"] = -1 if request.user.is_authenticated(): member = Member.objects.get(user=request.user) if member: context_dict["member"] = member categories = Category.objects.all() context_dict["categories"] = categories category_slug = request.GET.get("category", -1) if category_slug != -1: context_dict["selected_category"] = Category.objects.filter(slug=category_slug)[0].pk return render(request, "newthread.html", context_dict) else: return server_error(request)
def forgot_password(request): if request.method == "GET": if "user" in request.GET and "hash" in request.GET: return render(request, "changeforgot.html", {"username": request.GET["user"], "hash": request.GET["hash"]}) else: return render(request, "forgot.html") elif request.method == "POST": if "forgot" in request.POST: user = None if request.POST["username"] != "": user = User.objects.get(username=request.POST["username"]) elif request.POST["email"] != "": user = User.objects.get(email=request.POST["email"]) else: return render(request, "forgot.html", {"error": "Some Error Occurred"}) if user is not None: url = ( reverse("forgot-password") + "?user="******"&hash=" + hashlib.md5(user.password.encode("utf-8")).hexdigest() ) url = request.build_absolute_uri(url) message = "Hi " + user.first_name + ",\n" message += "Please visit following link to reset password\n" + url send_mail("Reset Password", message, "*****@*****.**", [user.email]) return render(request, "forgot.html", {"status": "Please check your email for reset password link"}) else: return render(request, "forgot.html", {"error": "No such user or email address"}) elif "change" in request.POST: user = User.objects.get(username=request.POST["username"]) if request.POST["hash"] == hashlib.md5(user.password.encode("utf-8")).hexdigest(): user.set_password(request.POST["password"]) user.save() request.session["status"] = "Successfully Changed Password" return redirect("/login/") else: return redirect("/") else: return render(request, "forgot.html") else: return server_error(request)
def profile_edit(request, slug): if request.method == "GET": if request.user.is_authenticated() and request.user == Member.objects.get(slug=slug).user: return render(request, "edit.html", {"member": Member.objects.get(slug=slug)}) return redirect("/") elif request.method == "POST": if "change" in request.POST: user = request.user user.first_name = request.POST["first_name"] user.last_name = request.POST["last_name"] member = Member.objects.get(user=user) member.date_of_birth = request.POST["dob"] member.location = request.POST["location"] member.bio = request.POST["bio"] member.details_visible = "visible" in request.POST user.save() member.save() return redirect("/profile/" + member.slug) return render(request, "profile.html", {"error": "Some error occurred"}) else: return server_error(request)
def register(request): """ register an openid. If user is already a member he can associate its openid with its account. A new account could also be created and automaticaly associated to the openid. url : /complete/ template : authopenid/complete.html """ is_redirect = False next = clean_next(request.GET.get("next")) openid_ = request.session.get("openid", None) if not openid_: return HttpResponseRedirect(reverse("user_signin") + next) nickname = openid_.sreg.get("nickname", "") email = openid_.sreg.get("email", "") form1 = OpenidRegisterForm(initial={"next": next, "username": nickname, "email": email}) form2 = OpenidVerifyForm(initial={"next": next, "username": nickname}) user_ = None if request.POST: just_completed = False if "bnewaccount" in request.POST.keys(): form1 = OpenidRegisterForm(request.POST) if form1.is_valid(): next = clean_next(form1.cleaned_data.get("next")) is_redirect = True tmp_pwd = User.objects.make_random_password() user_ = User.objects.create_user(form1.cleaned_data["username"], form1.cleaned_data["email"], tmp_pwd) # make association with openid uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id) uassoc.save() # login user_.backend = "django.contrib.auth.backends.ModelBackend" login(request, user_) elif "bverify" in request.POST.keys(): form2 = OpenidVerifyForm(request.POST) if form2.is_valid(): is_redirect = True next = clean_next(form2.cleaned_data.get("next")) user_ = form2.get_user() uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id) uassoc.save() login(request, user_) # check if we need to post a question that was added anonymously # this needs to be a function call becase this is also done # if user just logged in and did not need to create the new account if user_ != None and settings.EMAIL_VALIDATION == "on": send_new_email_key(user_, nomessage=True) output = validation_email_sent(request) set_email_validation_message(user_) # message set after generating view return output elif user_.is_authenticated(): return HttpResponseRedirect("/") else: raise server_error("") openid_str = str(openid_) bits = openid_str.split("/") base_url = bits[2] # assume this is base url url_bits = base_url.split(".") provider_name = url_bits[-2].lower() providers = { "yahoo": '<font color="purple">Yahoo!</font>', "flickr": '<font color="#0063dc">flick</font><font color="#ff0084">r</font>™', "google": "Google™", "aol": '<font color="#31658e">AOL</font>', } if provider_name not in providers: provider_logo = provider_name else: provider_logo = providers[provider_name] return render( "authopenid/complete.html", {"form1": form1, "form2": form2, "provider": provider_logo, "nickname": nickname, "email": email}, context_instance=RequestContext(request), )