How to use redirect_to method in wpt

Best JavaScript code snippet using wpt

main.py

Source:main.py Github

copy

Full Screen

1from flask import Flask, render_template, request, redirect, url_for, abort, session, jsonify2from datetime import datetime3import werkzeug4import url645from constants import *6from cred import get_cred7from utils import *8from db import reports_col, categories_col, admins_col9cred = get_cred()10app = Flask(__name__)11app.secret_key = cred["secret_key"]12@app.errorhandler(404)13def error_404(e):14 redirect_to = url64.encode(request.url)15 if request.url.startswith(API_ENTRYPOINT):16 return jsonify({17 "error": "404 Not Found",18 "description": "Resource not found - check url."19 }), 40420 else:21 return render_template("error.html", error_code="404", error_name="Nie znaleziono", error_desc="Niestety, nie istnieje strona, której szukasz. Sprawdź poprawność adresu URL.", admin=check_if_logged(), redirect_to=redirect_to)22@app.errorhandler(500)23def error_500(e):24 redirect_to = url64.encode(request.url)25 if request.url.startswith(API_ENTRYPOINT):26 return jsonify({27 "error": "500 Internal Server Error",28 "description": "Error in server code - please contact service admin."29 }), 50030 else:31 return render_template("error.html", error_code="500", error_name="Wewnętrzny Błąd Serwera", error_desc="Jest błąd w kodzie serwera. Powiadom administratora strony.", admin=check_if_logged(), redirect_to=redirect_to)32@app.route("/")33def index():34 redirect_to = url64.encode(request.url)35 return render_template("index.html", admin=check_if_logged(), redirect_to=redirect_to)36@app.route("/ranking")37def ranking():38 redirect_to = url64.encode(request.url)39 40 reports = reports_col.find({"verified": True})41 count = {}42 for reportdict in reports:43 try:44 count[reportdict["name"]] += 145 except KeyError:46 count[reportdict["name"]] = 147 48 result = rank(count)49 return render_template("ranking.html", ranking_reports=result, admin=check_if_logged(), redirect_to=redirect_to)50@app.route("/browse")51def browse():52 redirect_to = url64.encode(request.url)53 categories = cursor_to_list(categories_col.find({"accepted": True}))54 cat_map = {}55 for x in categories:56 cat_map[x["id"]] = x["name"]57 query = {}58 fields = {"name": "", "category_id": "", "category_name": "", "verified": ""}59 try:60 request.args["name"]61 except KeyError:62 pass63 else:64 query["name"] = {"$regex": request.args["name"].lower()}65 fields["name"] = request.args["name"].lower()66 try:67 request.args["category"]68 except KeyError:69 pass70 else:71 if request.args["category"] in cat_map.keys():72 query["category"] = request.args["category"]73 fields["category_id"] = request.args["category"]74 fields["category_name"] = cursor_to_list(categories_col.find({"id": request.args["category"]}), "name")[0]75 76 try:77 request.args["verified"]78 except KeyError:79 pass80 else:81 if request.args["verified"] == "verified":82 query["verified"] = True83 fields["verified"] = True84 elif request.args["verified"] == "unverified":85 query["verified"] = False86 fields["verified"] = False87 if query == {}:88 query = {"verified": True}89 fields["verified"] = True90 91 elements = cursor_to_list(reports_col.find(query))92 for i in range(len(elements)):93 elements[i]["category"] = cat_map[elements[i]["category"]]94 return render_template("browse.html",95 elements=elements,96 fields=fields,97 categories=categories,98 admin=check_if_logged(),99 redirect_to=redirect_to)100@app.route("/developer")101def developer():102 redirect_to = url64.encode(request.url)103 return render_template("developer.html", admin=check_if_logged(), redirect_to=redirect_to)104@app.route("/contact")105def contact():106 redirect_to = url64.encode(request.url)107 return render_template("contact.html", admin=check_if_logged(), redirect_to=redirect_to)108@app.route("/showreport/<reportid>")109def show_report(reportid):110 redirect_to = url64.encode(request.url)111 result = cursor_to_list(reports_col.find({"id": reportid}))112 if len(result) != 1:113 abort(404)114 cat_result = cursor_to_list(categories_col.find({"id": result[0]["category"]}))115 if len(cat_result) != 1:116 abort(500)117 category_name = cat_result[0]["name"]118 return render_template("show_report.html", reportdict=result[0], admin=check_if_logged(), category_name=category_name, redirect_to=redirect_to)119@app.route("/verifyreport/<reportid>")120def verify_report(reportid):121 redirect_to = url64.encode(request.url)122 result = cursor_to_list(reports_col.find({"id": reportid}))123 if len(result) != 1:124 abort(404)125 else:126 if check_if_logged():127 reports_col.update_one({"id": reportid}, {"$set": {128 "verified": True129 }})130 return redirect(url_for("show_report", reportid=reportid))131 else:132 return redirect(url_for("login"))133@app.route("/unverifyreport/<reportid>")134def unverify_report(reportid):135 redirect_to = url64.encode(request.url)136 result = cursor_to_list(reports_col.find({"id": reportid}))137 if len(result) != 1:138 abort(404)139 else:140 if check_if_logged():141 reports_col.update_one({"id": reportid}, {"$set": {142 "verified": False143 }})144 return redirect(url_for("show_report", reportid=reportid))145 else:146 return redirect(url_for("login"))147@app.route("/deletereport/<reportid>")148def delete_report(reportid):149 redirect_to = url64.encode(request.url)150 result = cursor_to_list(reports_col.find({"id": reportid}))151 if len(result) != 1:152 abort(404)153 else:154 if check_if_logged():155 reports_col.delete_one({"id": reportid})156 return redirect(url_for("browse"))157 else:158 return redirect(url_for("login"))159@app.route("/editreport/<reportid>", methods=["GET", "POST"])160def edit_report(reportid):161 redirect_to = url64.encode(request.url)162 result = cursor_to_list(reports_col.find({"id": reportid}))163 if len(result) != 1:164 abort(404)165 else:166 if not check_if_logged():167 return redirect(url_for("login"))168 else:169 if request.method == "POST":170 category = request.form.get("category", "")171 172 categories = cursor_to_list(categories_col.find({"accepted": True}))173 cat_map = {}174 for x in categories:175 cat_map[x["name"]] = x["id"]176 categories = cursor_to_list(categories, "name")177 if category == "" \178 or request.form["name"] == "" \179 or request.form["content"] == "" \180 or request.form["email"] == "":181 return render_template("report.html",182 reportdict=BLANK_REPORTDICT,183 field_error=True,184 categories=categories,185 admin=check_if_logged(),186 redirect_to=redirect_to)187 elif check_profanity(request.form["name"].lower()) or check_profanity(request.form["content"]):188 return render_template("report.html",189 reportdict=BLANK_REPORTDICT,190 profanity_found=True,191 categories=categories,192 admin=check_if_logged(),193 redirect_to=redirect_to)194 elif category not in categories:195 return render_template("report.html",196 reportdict=BLANK_REPORTDICT,197 field_error=True,198 categories=categories,199 admin=check_if_logged(),200 redirect_to=redirect_to)201 202 elif not valid_email(request.form["email"]):203 categories = cursor_to_list(categories_col.find({}), "name")204 return render_template("report.html",205 reportdict=BLANK_REPORTDICT,206 email_error=True,207 categories=categories,208 admin=check_if_logged(),209 redirect_to=redirect_to)210 else:211 edit_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")212 reports_col.update_one({"id": reportid}, {213 "$set": {214 "category": cat_map[request.form["category"]],215 "name": request.form["name"].lower(),216 "content": request.form["content"],217 "email": request.form["email"],218 "edittime": edit_time219 }220 })221 result = cursor_to_list(reports_col.find({"id": reportid}))222 if len(result) != 1:223 abort(404)224 return redirect(url_for("show_report", reportid=reportid))225 else:226 categories = cursor_to_list(categories_col.find({"accepted": True}), "name")227 result = cursor_to_list(reports_col.find({"id": reportid}))228 if len(result) != 1:229 abort(404)230 231 cat_result = cursor_to_list(categories_col.find({"id": result[0]["category"]}))232 if len(cat_result) != 1:233 abort(500)234 result[0]["category"] = cat_result[0]["name"]235 return render_template("edit_report.html",236 categories=categories,237 reportdict=result[0],238 admin=check_if_logged(),239 redirect_to=redirect_to)240@app.route("/report", methods=["GET", "POST"])241def report():242 redirect_to = url64.encode(request.url)243 if request.method == "POST":244 category = request.form.get("category", "")245 categories = cursor_to_list(categories_col.find({"accepted": True}))246 cat_map = {}247 for x in categories:248 cat_map[x["name"]] = x["id"]249 categories = cursor_to_list(categories, "name")250 if category == ""\251 or request.form["name"] == ""\252 or request.form["content"] == ""\253 or request.form["email"] == "":254 return render_template("report.html",255 reportdict=BLANK_REPORTDICT,256 categories=categories,257 field_error=True,258 admin=check_if_logged(),259 redirect_to=redirect_to)260 elif check_profanity(request.form["name"].lower()) or check_profanity(request.form["content"]):261 return render_template("report.html",262 reportdict=BLANK_REPORTDICT,263 profanity_found=True,264 categories=categories,265 admin=check_if_logged(),266 redirect_to=redirect_to)267 elif category not in categories:268 return render_template("report.html",269 reportdict=BLANK_REPORTDICT,270 field_error=True,271 categories=categories,272 admin=check_if_logged(),273 redirect_to=redirect_to)274 elif not valid_email(request.form["email"]):275 categories = cursor_to_list(categories_col.find({}), "name")276 return render_template("report.html",277 reportdict=BLANK_REPORTDICT,278 email_error=True,279 categories=categories,280 admin=check_if_logged(),281 redirect_to=redirect_to)282 else:283 insert_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")284 ids = cursor_to_list(reports_col.find(), "id")285 report_id = generate_id(ids)286 reports_col.insert_one({287 "id": report_id,288 "inserttime": insert_time,289 "edittime": insert_time,290 "category": cat_map[request.form["category"]],291 "name": request.form["name"].lower(),292 "content": request.form["content"],293 "email": request.form["email"],294 "verified": False295 })296 categories = cursor_to_list(categories_col.find({"accepted": True}), "name")297 return redirect(url_for("show_report", reportid=report_id))298 elif request.method == "GET":299 reportdict = request_args_to_dict({"category": "", "name": "", "content": "", "email": ""})300 categories = cursor_to_list(categories_col.find({"accepted": True}))301 cat_map = {"": ""}302 for x in categories:303 cat_map[x["id"]] = x["name"]304 categories = cursor_to_list(categories, "name")305 reportdict["category"] = cat_map[reportdict["category"]]306 return render_template("report.html", categories=categories, admin=check_if_logged(), reportdict=reportdict, redirect_to=redirect_to)307@app.route("/login", methods=["GET", "POST"])308def login():309 310 redirect_to = request.args.get("redirect", "")311 312 try:313 redirect_to_decoded = url64.decode(redirect_to)314 except:315 redirect_to_decoded = url_for("index")316 else:317 if redirect_to_decoded == "":318 redirect_to_decoded = url_for("index")319 if request.method == "POST":320 try:321 request.form["login"]322 request.form["password"]323 except werkzeug.exceptions.BadRequestKeyError:324 return render_template("login.html", field_error=True, admin=check_if_logged(), redirect_to=redirect_to)325 if request.form["login"] == "" or request.form["password"] == "":326 return render_template("login.html", field_error=True, admin=check_if_logged(), redirect_to=redirect_to)327 else:328 username = request.form["login"]329 password = request.form["password"]330 result = cursor_to_list(admins_col.find({"login": username}))331 for j in result:332 if check_hashed_psw(password, j["password"]):333 session["logged"] = True334 return redirect(redirect_to_decoded)335 return render_template("login.html", data_error=True, admin=check_if_logged(), redirect_to=redirect_to)336 else:337 if check_if_logged():338 return redirect(redirect_to_decoded)339 else:340 return render_template("login.html", admin=check_if_logged(), redirect_to=redirect_to)341@app.route("/logout")342def logout():343 344 redirect_to = request.args.get("redirect", "")345 346 try:347 redirect_to_decoded = url64.decode(redirect_to)348 except:349 redirect_to_decoded = url_for("index")350 else:351 if redirect_to_decoded == "":352 redirect_to_decoded = url_for("index")353 354 if check_if_logged():355 session.pop("logged", None)356 return redirect(redirect_to_decoded)357 else:358 return redirect(url_for("login", redirect_to=redirect_to))359@app.route("/suggestcategory", methods=["GET", "POST"])360def suggest_category():361 redirect_to = url64.encode(request.url)362 try:363 request.args["embed"]364 except KeyError:365 embed = False366 else:367 if request.args["embed"] == "true":368 embed = True369 else:370 embed = False371 if embed == True:372 if request.method == "POST":373 try:374 request.form["name"]375 except KeyError:376 return render_template("suggest_category_embed.html", field_error=True, admin=check_if_logged())377 else:378 category_name = request.form["name"].lower()379 380 if check_profanity(category_name):381 return render_template("suggest_category_embed.html", profanity_error=True, admin=check_if_logged())382 elif category_name in cursor_to_list(categories_col.find(), "name"):383 return render_template("suggest_category_embed.html", already_reported_error=True, admin=check_if_logged())384 elif category_name == "":385 return render_template("suggest_category_embed.html", field_error=True, admin=check_if_logged())386 387 categories_col.insert_one({388 "id": generate_id(cursor_to_list(categories_col.find({}), "id")),389 "name": category_name,390 "accepted": check_if_logged()391 })392 return_str = "close"393 if check_if_logged():394 return_str += " "395 return_str += category_name396 return return_str397 elif request.method == "GET":398 399 if embed:400 return render_template("suggest_category_embed.html", admin=check_if_logged())401 else:402 redirect_to = url64.encode(request.url)403 return render_template("suggest_category.html", admin=check_if_logged(), redirect_to=redirect_to)404 else:405 return render_template("suggest_category.html", admin=check_if_logged(), redirect_to=redirect_to)406@app.route("/admin")407def admin_panel():408 redirect_to = url64.encode(request.url)409 if check_if_logged():410 return render_template("admin_panel.html", admin=True, redirect_to=redirect_to)411 else:412 return redirect(url_for("login", redirect=redirect_to))413if __name__ == "__main__":...

Full Screen

Full Screen

helpers.py

Source:helpers.py Github

copy

Full Screen

...195 Otherwise, we go to the ?next= query param or to the dashboard if nothing else is196 specified.197 If THIRD_PARTY_AUTH_HINT is set, then `tpa_hint=<hint>` is added as a query parameter.198 """199 redirect_to = get_redirect_to(request)200 if not redirect_to:201 try:202 redirect_to = reverse('dashboard')203 except NoReverseMatch:204 redirect_to = reverse('home')205 if any(param in request.GET for param in POST_AUTH_PARAMS):206 # Before we redirect to next/dashboard, we need to handle auto-enrollment:207 params = [(param, request.GET[param]) for param in POST_AUTH_PARAMS if param in request.GET]208 params.append(('next', redirect_to)) # After auto-enrollment, user will be sent to payment page or to this URL209 redirect_to = '{}?{}'.format(reverse('finish_auth'), urllib.urlencode(params))210 # Note: if we are resuming a third party auth pipeline, then the next URL will already211 # be saved in the session as part of the pipeline state. That URL will take priority212 # over this one.213 # Append a tpa_hint query parameter, if one is configured214 tpa_hint = configuration_helpers.get_value(215 "THIRD_PARTY_AUTH_HINT",216 settings.FEATURES.get("THIRD_PARTY_AUTH_HINT", '')217 )218 if tpa_hint:219 # Don't add tpa_hint if we're already in the TPA pipeline (prevent infinite loop),220 # and don't overwrite any existing tpa_hint params (allow tpa_hint override).221 running_pipeline = third_party_auth.pipeline.get(request)222 (scheme, netloc, path, query, fragment) = list(urlparse.urlsplit(redirect_to))223 if not running_pipeline and 'tpa_hint' not in query:224 params = urlparse.parse_qs(query)225 params['tpa_hint'] = [tpa_hint]226 query = urllib.urlencode(params, doseq=True)227 redirect_to = urlparse.urlunsplit((scheme, netloc, path, query, fragment))228 return redirect_to229def get_redirect_to(request):230 """231 Determine the redirect url and return if safe232 :argument233 request: request object234 :returns: redirect url if safe else None235 """236 redirect_to = request.GET.get('next')237 header_accept = request.META.get('HTTP_ACCEPT', '')238 # If we get a redirect parameter, make sure it's safe i.e. not redirecting outside our domain.239 # Also make sure that it is not redirecting to a static asset and redirected page is web page240 # not a static file. As allowing assets to be pointed to by "next" allows 3rd party sites to241 # get information about a user on edx.org. In any such case drop the parameter.242 if redirect_to:243 mime_type, _ = mimetypes.guess_type(redirect_to, strict=False)...

Full Screen

Full Screen

old_redirect_urls.py

Source:old_redirect_urls.py Github

copy

Full Screen

1from django.conf.urls.defaults import patterns, url2from outside_spending_2014.feeds import FilingFeed, FilingsFeed, FilingsFormFeed, FilingsForms, CommitteeFormsFeed, SuperpacsForms3from django.views.generic.simple import direct_to_template, redirect_to4urlpatterns = patterns('',5 url(r'^$', redirect_to, {'url': 'http://realtime.influenceexplorer.com/pacs/#?ordering=-cash_on_hand&committee_class=UO'}),6 ## redirect to 2012 b/c there are no pages for 2014 yet. 7 url(r'^super-pacs/presidential/?$', redirect_to, {'url': '/outside-spending-2012/super-pacs/presidential/'}),8 url(r'^president-state-detail/(?P<state>[\w0]+)\/?$', redirect_to, {'url': '/outside-spending-2012/president-state-detail/%(state)s/'}),9 url(r'^races\/?$', redirect_to, {'url':'/outside-spending-2012/races/'}),10 url(r'^race_detail\/(?P<office>\w)\/(?P<state>[\w0]+)\/(?P<district>\d\d)\/?$', redirect_to, {'url':'/outside-spending-2012/race_detail/%(office)s/%(state)s/%(district)s/'}), 11 url(r'^overview\/?$', redirect_to, {'url':'/outside-spending-2012/overview/'}), 12 url(r'^october-club\/$', redirect_to, {'url':'/outside-spending-2012/october-club/'}), 13 url(r'^competitive-races\/$', redirect_to, {'url':'/outside-spending-2012/competitive-races/'}), 14 url(r'^electioneering-communications\/?$', redirect_to, {'url':'/outside-spending-2012/electioneering-communications/'}),15 url(r'^electioneering-groups\/?$', redirect_to, {'url':'/outside-spending-2012/electioneering-groups/'}), 16 url(r'^super-pacs/donating-organizations/', redirect_to, {'url':'/outside-spenders/2012/super-pacs/donating-organizations/'}), 17 url(r'^superpac-by-party\/', redirect_to, {'url': '/outside-spending-2012/by-affiliation/'}),18 url(r'^by-affiliation\/', redirect_to, {'url': '/outside-spending-2012/by-affiliation/'}),19 url(r'^by-spending', redirect_to, {'url': '/outside-spending-2012/by-spending/'}),20 url(r'^analytics\/',redirect_to, {'url': '/outside-spending-2012/analytics/'}),21 url(r'^superpac-chart-embed\/$', redirect_to, {'url': 'superpac-chart-embed'}),22 23 # most people are looking for old stuff24 url(r'^candidate\/(?P<candidate_slug>[\w-]+)\/(?P<candidate_id>[\w\d]+)\/?$', redirect_to, {'url':'/outside-spending-2012/candidate/%(candidate_slug)s/%(candidate_id)s/'}),25 url(r'^super-pacs/?$', redirect_to, {'url': 'http://realtime.influenceexplorer.com/pacs/#?ordering=-cash_on_hand&committee_class=UO'}),26 url(r'^all-outside-groups/?$', redirect_to, {'url': 'http://realtime.influenceexplorer.com/pacs/#?ordering=-total_disbursements&committee_class=I'}),27 28 url(r'^super-pacs/complete-list/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/pacs/#?ordering=-cash_on_hand&committee_class=UOVW'}),29 url(r'^committee\/(?P<committee_slug>[\w-]+)\/(?P<committee_id>C\d{8})\/?$', redirect_to, {'url': 'http://realtime.influenceexplorer.com/committee/%(committee_slug)s/%(committee_id)s/'}),30 31 url(r'^candidates\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/house/#?candidate_filter=all'}),32 33 34 url(r'^states\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/races/'}),35 url(r'^state\/(?P<state_abbreviation>\w\w)\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/outside-spending/#?ordering=-expenditure_date_formatted&candidate_state_checked=%(state_abbreviation)s/'}), 36 url(r'^independent-expenditures\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/outside-spending/'}),37 url(r'^file-downloads\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/download-index/'}), 38 39 ## REDIRECT TO FEC ALERTS --these shouldn't be linked anywhere, but...40 url(r'^recent-FEC-filings\/superpacs\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&committee_class=UO&time_range=cycle'}),41 url(r'^recent-FEC-filings\/superpacs\/new-F3X\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&committee_class=UO&time_range=cycle&report_type=monthly'}),42 url(r'^recent-FEC-filings\/independent-expenditures\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&time_range=cycle&report_type=ies'}), 43 url(r'^recent-FEC-filings\/significant-committees\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&time_range=cycle'}),44 url(r'^recent-FEC-filings\/significant-committees\/new-periodic\/?$',redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&time_range=cycle'}),45 url(r'^recent-FEC-filings\/48-hr-reports\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/#?ordering=-filing_number&time_range=cycle&report_type=F6'}),46 url(r'^recent-FEC-filings\/?$', redirect_to, {'url':'http://realtime.influenceexplorer.com/newest-filings/'}),47 48 ## feeds -- same url, but now served from fec-alerts and powerd by 2014 data 49 url(r'^recent-FEC-filings\/feeds\/committee\/(?P<committee_id>C\d+)/$', FilingFeed()), 50 url(r'^recent-FEC-filings\/feeds\/committee\/(?P<committee_id>C\d+)/forms/(?P<form_types>[\w\d\-]+)/$', CommitteeFormsFeed()),51 url(r'^recent-FEC-filings\/feeds\/committees\/(?P<committee_ids>[C\d\-]+)/$', FilingsFeed()), 52 url(r'^recent-FEC-filings\/feeds\/committees\/(?P<committee_ids>[C\d\-]+)/forms/(?P<form_types>[\w\d\-]+)/$', FilingsFormFeed()),53 url(r'^recent-FEC-filings\/feeds\/forms/(?P<form_types>[\w\d\-]+)/$', FilingsForms()),54 url(r'^recent-FEC-filings\/feeds\/superpacs\/forms/(?P<form_types>[\w\d\-]+)/$', SuperpacsForms()), 55 56 57 url(r'^noncommittees\/$', 'outside_spending.views.noncommittees'),58 url(r'^maintenance/', direct_to_template, {'template': 'outside_spending/maintenance.html'}),59 url(r'^search\/$', 'outside_spending.views.search'),60 url(r'^more-resources\/$', 'outside_spending.views.more_resources'),61)62### CSV FILES63# url(r'^csv/committee\/[\w-]+\/(?P<committee_id>C\d{8})\/?$', 'outside_spending.views.expenditure_csv'),64# url(r'^csv/contributions\/[\w-]+\/(?P<committee_id>C\d{8})\/?$', 'outside_spending.views.contribs_csv'),65# url(r'^csv/organizational-contributions\/$', 'outside_spending.views.organizational_contribs_csv'), 66# url(r'^csv/all/?$', 'outside_spending.views.all_contribs_csv'), 67# url(r'^csv/all/expenditures\/?$', 'outside_spending.views.all_expenditures_csv'), 68# url(r'^csv/state/(\w\w)\/?$', 'outside_spending.views.state_contribs_csv'),69# url(r'^csv/state/expenditures/(\w\w)\/?$', 'outside_spending.views.expenditure_csv_state'),70# url(r'^csv/race/expenditures/(?P<office>\w)\/(?P<state>[\w0]+)\/(?P<district>\d\d)\/?$', 'outside_spending.views.expenditure_csv_race'),71# url(r'^csv/committees\/$', 'outside_spending.views.committee_summary_public'),72# url(r'^csv/committees-all-details\/$', 'outside_spending.views.committee_summary_private'),73# url(r'^csv/superpac-political-orientation\/$', 'outside_spending.views.superpac_political_orientation'),...

Full Screen

Full Screen

member_decorators.py

Source:member_decorators.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-23__author__ = 'chuter'45from django.http import HttpResponseRedirect6from webapp.models import Workspace7from models import *89def member_required(function=None, redirect_to=None, is_format_webapp_id_in_url=True):10 def _dec(view_func):11 def _view(request, *args, **kwargs):12 if not hasattr(request, 'member') or request.member is None:13 redirect_to = _view.redirect_to1415 if redirect_to is None:16 #redirect_to = "http://{}/".format(request.META['HTTP_HOST'])17 project_id = 018 for workspace in Workspace.objects.filter(owner_id=request.webapp_owner_id):19 if workspace.inner_name == 'home_page':20 project_id = workspace.template_project_id21 redirect_to = "/workbench/jqm/preview/?project_id=%d" % project_id2223 work_space_id = request.REQUEST.get('workspace_id', '')24 redirect_to = "{}&workspace_id={}&webapp_owner_id={}".format(25 redirect_to,26 work_space_id,27 request.user_profile.user_id28 )2930 if _view.is_format_webapp_id_in_url:31 redirect_to = redirect_to.format(request.user_profile.webapp_id)3233 return HttpResponseRedirect(redirect_to) 34 35 return view_func(request, *args, **kwargs)3637 _view.__doc__ = view_func.__doc__38 _view.__dict__ = view_func.__dict__39 _view.__dict__['redirect_to'] = redirect_to40 _view.__dict__['is_format_webapp_id_in_url'] = is_format_webapp_id_in_url4142 _view.__name__ = view_func.__name__4344 return _view4546 if function is None:47 return _dec48 else:49 return _dec(function)5051 # elif 52 53# WEBAPP_USER_CENTER_URI = 'module=user_center&model=user_info&action=get&workspace_id=user_center'54# def binding_required(function=None, ignore_wechat_login=True):55# def _dec(view_func):56# def _view(request, *args, **kwargs):57# ignore_wechat_login = _view.ignore_wechat_login58# if ignore_wechat_login is True:59# ignore_wechat_login = False if request.GET.get('wechat_login', '0') == '1' else True6061# if hasattr(request, 'member') and request.member and ignore_wechat_login is False:62# MemberInfo.objects.filter(member_id=request.member.id).update(is_passed=True)6364# if ignore_wechat_login is False:65# redirect_to = ''66# else:67# if request.member:68# member_info = MemberInfo.get_member_info(request.member.id)69# if WEBAPP_USER_CENTER_URI in request.get_full_path():70# if member_info.is_passed or member_info.is_binded:71# redirect_to = ''72# else:73# redirect_to = "/workbench/jqm/preview/?module=user_center&model=binding_page&action=get&webapp_owner_id={}".format(74# request.user_profile.user_id75# )76# else:77# redirect_to = ''78# else:79# redirect_to = "/workbench/jqm/preview/?module=user_center&model=binding_page&action=get&webapp_owner_id={}".format(80# request.user_profile.user_id81# )8283# if redirect_to:84# return HttpResponseRedirect(redirect_to) 85# else:86# return view_func(request, *args, **kwargs)8788# _view.__doc__ = view_func.__doc__89# _view.__dict__ = view_func.__dict__90# _view.__dict__['ignore_wechat_login'] = ignore_wechat_login9192# return _view9394# if function is None:95# return _dec96# else: ...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

...5from django.http import HttpResponseRedirect6from django.utils.translation import ugettext as _7from google.appengine.api import users8from ragendja.template import render_to_response9def get_redirect_to(request, redirect_field_name):10 redirect_to = request.REQUEST.get(redirect_field_name)11 # Light security check -- make sure redirect_to isn't garbage.12 if not redirect_to or '//' in redirect_to or ' ' in redirect_to:13 redirect_to = settings.LOGIN_REDIRECT_URL14 return redirect_to15def google_login(request, template_name=None,16 redirect_field_name=REDIRECT_FIELD_NAME):17 redirect_to = get_redirect_to(request, redirect_field_name)18 return HttpResponseRedirect(users.create_login_url(redirect_to))19def hybrid_login(request, template_name='registration/login.html',20 redirect_field_name=REDIRECT_FIELD_NAME):21 # Don't login using both authentication systems at the same time22 if request.user.is_authenticated():23 redirect_to = get_redirect_to(request, redirect_field_name)24 return HttpResponseRedirect(redirect_to)25 return login(request, template_name, redirect_field_name)26def google_logout(request, next_page=None,27 template_name='registration/logged_out.html'):28 if users.get_current_user():29 # Redirect to this page until the session has been cleared.30 logout_url = users.create_logout_url(next_page or request.path)31 return HttpResponseRedirect(logout_url)32 if not next_page:33 return render_to_response(request, template_name,34 {'title': _('Logged out')})35 return HttpResponseRedirect(next_page)36def hybrid_logout(request, next_page=None,37 template_name='registration/logged_out.html'):...

Full Screen

Full Screen

admin.py

Source:admin.py Github

copy

Full Screen

1from django.conf import settings2from django.contrib import admin3from django.contrib.admin import AdminSite4from django.contrib.auth import REDIRECT_FIELD_NAME5from django.contrib.auth.views import redirect_to_login6from django.shortcuts import resolve_url7from django.utils.http import is_safe_url8from .models import PhoneDevice9from .utils import monkeypatch_method10class AdminSiteOTPRequiredMixin(object):11 """12 Mixin for enforcing OTP verified staff users.13 Custom admin views should either be wrapped using :meth:`admin_view` or14 use :meth:`has_permission` in order to secure those views.15 """16 def has_permission(self, request):17 """18 Returns True if the given HttpRequest has permission to view19 *at least one* page in the admin site.20 """21 if not super().has_permission(request):22 return False23 return request.user.is_verified()24 def login(self, request, extra_context=None):25 """26 Redirects to the site login page for the given HttpRequest.27 """28 redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))29 if not redirect_to or not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):30 redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)31 return redirect_to_login(redirect_to)32class AdminSiteOTPRequired(AdminSiteOTPRequiredMixin, AdminSite):33 """34 AdminSite enforcing OTP verified staff users.35 """36 pass37def patch_admin():38 @monkeypatch_method(AdminSite)39 def login(self, request, extra_context=None):40 """41 Redirects to the site login page for the given HttpRequest.42 """43 redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))44 if not redirect_to or not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):45 redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)46 return redirect_to_login(redirect_to)47def unpatch_admin():48 setattr(AdminSite, 'login', original_login)49original_login = AdminSite.login50class PhoneDeviceAdmin(admin.ModelAdmin):51 """52 :class:`~django.contrib.admin.ModelAdmin` for53 :class:`~two_factor.models.PhoneDevice`.54 """55 raw_id_fields = ('user',)...

Full Screen

Full Screen

urls.py

Source:urls.py Github

copy

Full Screen

1from django.conf.urls.defaults import *2from django.views.generic.simple import redirect_to3import views4urlpatterns = patterns('',5 (r'^no_template_view/$', views.no_template_view),6 (r'^staff_only/$', views.staff_only_view),7 (r'^get_view/$', views.get_view),8 (r'^request_data/$', views.request_data),9 (r'^request_data_extended/$', views.request_data, {'template':'extended.html', 'data':'bacon'}),10 url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'),11 (r'^login_protected_redirect_view/$', views.login_protected_redirect_view),12 (r'^redirects/$', redirect_to, {'url': '/test_client_regress/redirects/further/'}),13 (r'^redirects/further/$', redirect_to, {'url': '/test_client_regress/redirects/further/more/'}),14 (r'^redirects/further/more/$', redirect_to, {'url': '/test_client_regress/no_template_view/'}),15 (r'^redirect_to_non_existent_view/$', redirect_to, {'url': '/test_client_regress/non_existent_view/'}),16 (r'^redirect_to_non_existent_view2/$', redirect_to, {'url': '/test_client_regress/redirect_to_non_existent_view/'}),17 (r'^redirect_to_self/$', redirect_to, {'url': '/test_client_regress/redirect_to_self/'}),18 (r'^circular_redirect_1/$', redirect_to, {'url': '/test_client_regress/circular_redirect_2/'}),19 (r'^circular_redirect_2/$', redirect_to, {'url': '/test_client_regress/circular_redirect_3/'}),20 (r'^circular_redirect_3/$', redirect_to, {'url': '/test_client_regress/circular_redirect_1/'}),21 (r'^set_session/$', views.set_session_view),22 (r'^check_session/$', views.check_session_view),23 (r'^request_methods/$', views.request_methods_view),24 (r'^check_unicode/$', views.return_unicode),25 (r'^parse_unicode_json/$', views.return_json_file),26 (r'^check_headers/$', views.check_headers),27 (r'^check_headers_redirect/$', redirect_to, {'url': '/test_client_regress/check_headers/'}),...

Full Screen

Full Screen

mp_decorators.py

Source:mp_decorators.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-23__author__ = 'bert'45from django.http import HttpResponseRedirect67def mp_required(function=None, redirect_to=None):8 def _dec(view_func):9 def _view(request, *args, **kwargs):10 if hasattr(request, 'user') and request.user:11 redirect_to = _view.redirect_to1213 # user_profile = request.user.get_profile()14 user_profile = request.manager.get_profile()15 if user_profile and user_profile.is_mp_registered is False:16 redirect_to= '/new_weixin/mp_user/'17 # if redirect_to is None:18 # #redirect_to = "http://{}/".format(request.META['HTTP_HOST'])19 # project_id = 020 # for workspace in Workspace.objects.filter(owner_id=request.webapp_owner_id):21 # if workspace.inner_name == 'home_page':22 # project_id = workspace.template_project_id23 # redirect_to = "/workbench/jqm/preview/?project_id=%d" % project_id2425 # work_space_id = request.REQUEST.get('workspace_id', '')26 # redirect_to = "{}&workspace_id={}&webapp_owner_id={}".format(27 # redirect_to,28 # work_space_id,29 # request.user_profile.user_id30 # )3132 # if _view.is_format_webapp_id_in_url:33 # redirect_to = redirect_to.format(request.user_profile.webapp_id)3435 return HttpResponseRedirect(redirect_to) 36 # else:37 # TODO 处理跳转??38 return view_func(request, *args, **kwargs)3940 _view.__doc__ = view_func.__doc__41 _view.__dict__ = view_func.__dict__42 _view.__dict__['redirect_to'] = redirect_to43 #4445 _view.__name__ = view_func.__name__4647 return _view4849 if function is None:50 return _dec51 else: ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org', 'A.1234567890123456789012345678901234567890');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 test.redirect_to(data.data.testId, function(err, data) {8 console.log(data);9 });10 }11});12{ statusCode: 200,13 { statusCode: 200,14 { testId: '150407_6Y_1R',15 runs: 1 } }16{ statusCode: 200,17 { statusCode: 200,18 { testId: '150407_6Y_1R',

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org', 'A.1234567890123456789012345678901234567890');3}, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data.data.runs[1].firstView);8 }9});10var wpt = require('webpagetest');11var test = wpt('www.webpagetest.org', 'A.1234567890123456789012345678901234567890');12}, function(err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data.data.runs[1].firstView);17 }18});19var wpt = require('webpagetest');20var test = wpt('www.webpagetest.org', 'A.1234567890123456789012345678901234567890');21}, function(err, data) {22 if (err) {23 console.log(err);24 } else {25 console.log(data.data.runs[1].firstView);26 }27});28var wpt = require('webpagetest');29var test = wpt('www.webpagetest.org', 'A.1234567890123456789012345678901234567890');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 wpt.redirect_to(data.data.testId, function(err, data) {8 if (err) {9 console.log(err);10 } else {11 console.log(data);12 }13 });14 }15});16{ statusCode: 200,17{ statusCode: 200,18 if (err) {19 console.log(err);20 } else {21 console.log(data);22 }23});24{ statusCode: 200,25 data: 'Test Complete' }26{ statusCode: 200,27 if (err) {28 console.log(err);29 } else {30 console.log(data);31 }

Full Screen

Using AI Code Generation

copy

Full Screen

1wpt.setHeader("X-My-Header", "my value");2wpt.setCookie("mycookie", "my value");3wpt.setHeader("X-My-Header", "my value");4wpt.setCookie("mycookie", "my value");5wpt.setHeader("X-My-Header", "my value");6wpt.setCookie("mycookie", "my value");7wpt.setHeader("X-My-Header", "my value");8wpt.setCookie("mycookie", "my value");9wpt.setHeader("X-My-Header", "my value");10wpt.setCookie("mycookie", "my value");11wpt.setHeader("X-My-Header", "my value");12wpt.setCookie("mycookie", "my value");13wpt.setHeader("X-My-Header", "my value");14wpt.setCookie("mycookie", "my value");15wpt.setHeader("X-My-Header", "my

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful