本文整理匯總了Python中flask.request.url方法的典型用法代碼示例。如果您正苦於以下問題:Python request.url方法的具體用法?Python request.url怎麽用?Python request.url使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.request
的用法示例。
在下文中一共展示了request.url方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update_content_in_local_cache
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def update_content_in_local_cache(url, content, method='GET'):
"""更新 local_cache 中緩存的資源, 追加content
在stream模式中使用"""
if local_cache_enable and method == 'GET' and cache.is_cached(url):
info_dict = cache.get_info(url)
resp = cache.get_obj(url)
resp.set_data(content)
# 當存儲的資源沒有完整的content時, without_content 被設置為true
# 此時該緩存不會生效, 隻有當content被添加後, 緩存才會實際生效
# 在stream模式中, 因為是先接收http頭, 然後再接收內容, 所以會出現隻有頭而沒有內容的情況
# 此時程序會先將隻有頭部的響應添加到本地緩存, 在內容實際接收完成後再追加內容
info_dict['without_content'] = False
if verbose_level >= 4: dbgprint('LocalCache_UpdateCache', url, content[:30], len(content))
cache.put_obj(
url,
resp,
obj_size=len(content),
expires=get_expire_from_mime(parse.mime),
last_modified=info_dict.get('last_modified'),
info_dict=info_dict,
)
示例2: try_get_cached_response
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def try_get_cached_response(url, client_header=None):
"""
嘗試從本地緩存中取出響應
:param url: real url with query string
:type client_header: dict
:rtype: Union[Response, None]
"""
# Only use cache when client use GET
if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
if client_header is not None and 'if-modified-since' in client_header and \
cache.is_unchanged(url, client_header.get('if-modified-since', None)):
dbgprint('FileCacheHit-304', url)
return generate_304_response()
else:
cached_info = cache.get_info(url)
if cached_info.get('without_content', True):
# 關於 without_content 的解釋, 請看update_content_in_local_cache()函數
return None
# dbgprint('FileCacheHit-200')
resp = cache.get_obj(url)
assert isinstance(resp, Response)
parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
return resp
else:
return None
示例3: extract_url_path_and_query
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def extract_url_path_and_query(full_url=None, no_query=False):
"""
Convert http://foo.bar.com/aaa/p.html?x=y to /aaa/p.html?x=y
:param no_query:
:type full_url: str
:param full_url: full url
:return: str
"""
if full_url is None:
full_url = request.url
split = urlsplit(full_url)
result = split.path or "/"
if not no_query and split.query:
result += '?' + split.query
return result
# ################# End Client Request Handler #################
# ################# Begin Middle Functions #################
示例4: request_remote_site
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def request_remote_site():
"""
請求遠程服務器(high-level), 並在返回404/500時進行 domain_guess 嘗試
"""
# 請求被鏡像的網站
# 注意: 在zmirror內部不會處理重定向, 重定向響應會原樣返回給瀏覽器
parse.remote_response = send_request(
parse.remote_url,
method=request.method,
headers=parse.client_header,
data=parse.request_data_encoded,
)
if parse.remote_response.url != parse.remote_url:
warnprint("requests's remote url", parse.remote_response.url,
'does no equals our rewrited url', parse.remote_url)
if 400 <= parse.remote_response.status_code <= 599:
# 猜測url所對應的正確域名
dbgprint("Domain guessing for", request.url)
result = guess_correct_domain()
if result is not None:
parse.remote_response = result
示例5: query
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
"""Execute SPARQL query for a specific grlc-generated API endpoint"""
glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
glogger.debug("Request accept header: " + request.headers["Accept"])
requestArgs = request.args
acceptHeader = request.headers['Accept']
requestUrl = request.url
formData = request.form
query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
sha=sha, content=content, requestArgs=requestArgs,
acceptHeader=acceptHeader,
requestUrl=requestUrl, formData=formData)
if isinstance(query_response, list):
query_response = jsonify(query_response)
return make_response(query_response, status, headers)
### Server routes ###
示例6: do_POST
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def do_POST(self, service=""):
log.debug("NebHookServer: Plugin=%s : Incoming request from %s",
service, request.remote_addr)
if service.split("/")[0] not in self.plugin_mappings:
return ("", 404, {})
plugin = self.plugin_mappings[service.split("/")[0]]
try:
# tuple (body, status_code, headers)
response = plugin.on_receive_webhook(
request.url,
request.get_data(),
request.remote_addr,
request.headers
)
if response:
return response
return ("", 200, {})
except Exception as e:
log.exception(e)
return ("", 500, {})
示例7: google_login
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def google_login():
# to avoid flask-login displaying the login error message
session.pop("_flashes", None)
next_url = request.args.get("next")
# Google does not allow to append param to redirect_url
# we need to pass the next url by session
if next_url:
session["google_next_url"] = next_url
google = OAuth2Session(GOOGLE_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri)
authorization_url, state = google.authorization_url(_authorization_base_url)
# State is used to prevent CSRF, keep this for later.
session["oauth_state"] = state
return redirect(authorization_url)
示例8: facebook_login
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def facebook_login():
# to avoid flask-login displaying the login error message
session.pop("_flashes", None)
next_url = request.args.get("next")
# Facebook does not allow to append param to redirect_uri
# we need to pass the next url by session
if next_url:
session["facebook_next_url"] = next_url
facebook = OAuth2Session(
FACEBOOK_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri
)
facebook = facebook_compliance_fix(facebook)
authorization_url, state = facebook.authorization_url(_authorization_base_url)
# State is used to prevent CSRF, keep this for later.
session["oauth_state"] = state
return redirect(authorization_url)
示例9: callback
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def callback():
""" Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
simplelogin = OAuth2Session(client_id, state=session["oauth_state"])
token = simplelogin.fetch_token(
token_url, client_secret=client_secret, authorization_response=request.url
)
# At this point you can fetch protected resources but lets save
# the token and show how this is done from a persisted token
# in /profile.
session["oauth_token"] = token
return redirect(url_for(".profile"))
示例10: post
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def post(self):
data = request.get_json()
project = data['project']
model = data['model']
name = data['name']
url = data['url']
headers = data['headers']
xieyi = data['xieyi']
meth = data['meth']
project_id = Project.query.filter_by(project_name=project).first().id
models_id = Model.query.filter_by(model_name=model).first().id
try:
new_interface = Interface(model_id=models_id, projects_id=project_id,
Interface_name=name,
Interface_url=url,
Interface_meth=meth,
Interface_user_id=current_user.id,
Interface_headers=headers,
interfacetype=xieyi)
db.session.add(new_interface)
db.session.commit()
return jsonify({'data': interface_add_success, 'code': 2})
except Exception as e:
db.session.rollback()
return jsonify({'data': interface_add_erroe, 'code': 3})
示例11: callback
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def callback(self):
"""A method which should be always called after completing authorization code grant process
usually in callback view.
It fetches the authorization token and saves it flask
`session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_ object.
"""
if request.values.get("error"):
return request.values["error"]
discord = self._make_session(state=session.get("DISCORD_OAUTH2_STATE"))
token = discord.fetch_token(
configs.DISCORD_TOKEN_URL,
client_secret=self.client_secret,
authorization_response=request.url
)
self._token_updater(token)
示例12: require_login
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def require_login(self, view_func):
"""
Use this to decorate view functions that require a user to be logged
in. If the user is not already logged in, they will be sent to the
Provider to log in, after which they will be returned.
.. versionadded:: 1.0
This was :func:`check` before.
"""
@wraps(view_func)
def decorated(*args, **kwargs):
if g.oidc_id_token is None:
return self.redirect_to_auth_server(request.url)
return view_func(*args, **kwargs)
return decorated
# Backwards compatibility
示例13: validate_token
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def validate_token(self, token, scopes_required=None):
"""
This function can be used to validate tokens.
Note that this only works if a token introspection url is configured,
as that URL will be queried for the validity and scopes of a token.
:param scopes_required: List of scopes that are required to be
granted by the token before returning True.
:type scopes_required: list
:returns: True if the token was valid and contained the required
scopes. An ErrStr (subclass of string for which bool() is False) if
an error occured.
:rtype: Boolean or String
.. versionadded:: 1.1
"""
valid = self._validate_token(token, scopes_required)
if valid is True:
return True
else:
return ErrStr(valid)
示例14: bookmarklet_js
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def bookmarklet_js():
base_url = request.url.replace(
"browser-tools/bookmarklet.js",
"static/browser-tools/"
)
if "localhost:" not in base_url:
# seems like this shouldn't be necessary. but i think
# flask's request.url is coming in with http even when
# we asked for https on the server. weird.
base_url = base_url.replace("http://", "https://")
rendered = render_template(
"browser-tools/bookmarklet.js",
base_url=base_url
)
resp = make_response(rendered, 200)
resp.mimetype = "application/javascript"
return resp
示例15: upload_file
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import url [as 別名]
def upload_file():
"""Return File Upload flask app analysis blueprint."""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also submit a empty part without filename
if file.filename == '':
flash('No selected file, or that file type is not supported')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_hash = get_upload_file_hash(file)
flash("The " + str(filename) + " md5:" + file_hash + " has been uploaded!")
return render_template('upload_file.html', title='Upload File')