Python flask.request.host() Examples
The following are 30
code examples of flask.request.host().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask.request
, or try the search function
.
Example #1
Source File: csrf.py From jbox with MIT License | 8 votes |
def protect(self): if request.method not in self._app.config['WTF_CSRF_METHODS']: return if not validate_csrf(self._get_csrf_token()): reason = 'CSRF token missing or incorrect.' return self._error_response(reason) if request.is_secure and self._app.config['WTF_CSRF_SSL_STRICT']: if not request.referrer: reason = 'Referrer checking failed - no Referrer.' return self._error_response(reason) good_referrer = 'https://%s/' % request.host if not same_origin(request.referrer, good_referrer): reason = 'Referrer checking failed - origin does not match.' return self._error_response(reason) request.csrf_valid = True # mark this request is csrf valid
Example #2
Source File: work_order.py From sparrow with GNU General Public License v3.0 | 6 votes |
def work_sql_execute_details(work_number=None): publish_info = defaultdict() try: db_sso = db_op.user_sso db_sql_execute = db_op.sql_execute if work_number: infos = db_sso.query.with_entities(db_sso.dingunionid, db_sso.realName, db_sso.department).all() users = {info[0]: info[1:] for info in infos} sql_execute= db_sql_execute.query.with_entities(db_sql_execute.date, db_sql_execute.time, db_sql_execute.host, db_sql_execute.port, db_sql_execute.database, db_sql_execute.sql_url, db_sql_execute.sql_md5, db_sql_execute.describe, db_sql_execute.dingid).filter(db_sql_execute.work_number==int(work_number)).all() if sql_execute: publish_info['sql_execute'] = sql_execute[0] publish_info['user_info'] = users[sql_execute[0][-1]] except Exception as e: logging.error(e) return render_template('sql_execute_details.html', publish_info=publish_info)
Example #3
Source File: csrf.py From RSSNewsGAE with Apache License 2.0 | 6 votes |
def protect(self): if request.method not in current_app.config['WTF_CSRF_METHODS']: return try: validate_csrf(self._get_csrf_token()) except ValidationError as e: logger.info(e.args[0]) self._error_response(e.args[0]) if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']: if not request.referrer: self._error_response('The referrer header is missing.') good_referrer = 'https://{0}/'.format(request.host) if not same_origin(request.referrer, good_referrer): self._error_response('The referrer does not match the host.') g.csrf_valid = True # mark this request as CSRF valid
Example #4
Source File: core.py From swagger-ui-py with Apache License 2.0 | 6 votes |
def get_config(self, host): if self._config_path: assert Path(self._config_path).is_file() with open(self._config_path, 'rb') as config_file: config = self._load_config(config_file.read()) elif self._config_url: with urllib.request.urlopen(self._config_url) as config_file: config = self._load_config(config_file.read()) if StrictVersion(config.get('openapi', '2.0.0')) >= StrictVersion('3.0.0'): for server in config['servers']: server['url'] = re.sub(r'//[a-z0-9\-\.:]+/?', '//{}/'.format(host), server['url']) elif 'host' not in config: config['host'] = host return config
Example #5
Source File: core.py From swagger-ui-py with Apache License 2.0 | 6 votes |
def _aiohttp_handler(self): from aiohttp import web async def swagger_doc_handler(request): return web.Response(text=self.doc_html, content_type='text/html') async def swagger_editor_handler(request): return web.Response(text=self.editor_html, content_type='text/html') async def swagger_config_handler(request): return web.json_response(self.get_config(request.host)) self._app.router.add_get(self._uri(), swagger_doc_handler) self._app.router.add_get(self._uri('/'), swagger_doc_handler) if self._editor: self._app.router.add_get(self._uri('/editor'), swagger_editor_handler) self._app.router.add_get(self._uri('/swagger.json'), swagger_config_handler) self._app.router.add_static(self._uri('/'), path='{}/'.format(self.static_dir))
Example #6
Source File: core.py From swagger-ui-py with Apache License 2.0 | 6 votes |
def _sanic_handler(self): from sanic import response from sanic.blueprints import Blueprint swagger_blueprint = Blueprint('swagger_blueprint', url_prefix=self._url_prefix) @swagger_blueprint.get('/') async def swagger_blueprint_doc_handler(request): return response.html(self.doc_html) if self._editor: @swagger_blueprint.get('/editor') async def swagger_blueprint_editor_handler(request): return response.html(self.editor_html) @swagger_blueprint.get('/swagger.json') async def swagger_blueprint_config_handler(request): return response.json(self.get_config(request.host)) swagger_blueprint.static('/', str(self.static_dir)) self._app.blueprint(swagger_blueprint)
Example #7
Source File: main.py From --Awesome-Python-- with GNU General Public License v3.0 | 5 votes |
def before_request(): # 매 요청의 처리 이전에 호출 print('Before request') g.host = request.host g.remote_addr = request.remote_addr
Example #8
Source File: models.py From web_develop with GNU General Public License v3.0 | 5 votes |
def get_url(self, subtype, is_symlink=False): hash_or_link = self.symlink if is_symlink else self.filehash return 'http://{host}/{subtype}/{hash_or_link}'.format( subtype=subtype, host=request.host, hash_or_link=hash_or_link)
Example #9
Source File: models.py From web_develop with GNU General Public License v3.0 | 5 votes |
def get_url(self, subtype, is_symlink=False): hash_or_link = self.symlink if is_symlink else self.filehash return 'http://{host}/{subtype}/{hash_or_link}'.format( subtype=subtype, host=request.host, hash_or_link=hash_or_link)
Example #10
Source File: app.py From web_develop with GNU General Public License v3.0 | 5 votes |
def get_url(self, subtype, is_symlink=False): hash_or_link = self.symlink if is_symlink else self.filehash return 'http://{host}/{subtype}/{hash_or_link}'.format( subtype=subtype, host=request.host, hash_or_link=hash_or_link)
Example #11
Source File: views.py From gutenberg-http with Apache License 2.0 | 5 votes |
def index(): return redirect('{test_page_url}?server={server}'.format( test_page_url=config.TEST_PAGE_URL, server=quote(request.host)))
Example #12
Source File: archivenow.py From archivenow with MIT License | 5 votes |
def pushit(path): # no path; return a list of avaliable archives if path == '': #resp = jsonify(listArchives_server(handlers)) #resp.status_code = 200 return render_template('index.html') #return resp # get request with path elif (path == 'api'): resp = jsonify(listArchives_server(handlers)) resp.status_code = 200 return resp elif (path == "ajax-loader.gif"): return render_template('ajax-loader.gif') else: try: # get the args passed to push function like API KEY if provided PUSH_ARGS = {} for k in request.args.keys(): PUSH_ARGS[k] = request.args[k] s = str(path).split('/', 1) arc_id = s[0] URI = request.url.split('/', 4)[4] # include query params, too if 'herokuapp.com' in request.host: PUSH_ARGS['from_heroku'] = True # To push into archives resp = {"results": push(URI, arc_id, PUSH_ARGS)} if len(resp["results"]) == 0: return bad_request() else: # what to return resp = jsonify(resp) resp.status_code = 200 return resp except Exception as e: pass return bad_request()
Example #13
Source File: archivenow.py From archivenow with MIT License | 5 votes |
def start(port=SERVER_PORT, host=SERVER_IP): global SERVER_PORT global SERVER_IP SERVER_PORT = port SERVER_IP = host app.run( host=host, port=port, threaded=True, debug=True, use_reloader=False)
Example #14
Source File: 8. Other Data - request.headers & request.uri & etc.py From --Awesome-Python-- with GNU General Public License v3.0 | 5 votes |
def index(): # request 객체에는 수많은 속성들이 존재한다 # werkzeug.wrappers.BaseRequest에서 @cached_property나 @property로 처리된 프로퍼티들에 접근할 수 있다 print(request.host, request.remote_addr) print(request.method, request.uri, request.full_url) print(request.headers) print(request.is_xhr) return 'hello'
Example #15
Source File: work_order.py From sparrow with GNU General Public License v3.0 | 5 votes |
def work_application_details(work_number=None): publish_info = defaultdict() try: db_sso = db_op.user_sso db_publish_application = db_op.publish_application db_sql_execute = db_op.sql_execute if work_number: infos = db_sso.query.with_entities(db_sso.dingunionid, db_sso.realName, db_sso.department).all() users = {info[0]: info[1:] for info in infos} task_records = db_publish_application.query.with_entities(db_publish_application.date, db_publish_application.time, db_publish_application.project, db_publish_application.version, db_publish_application.git_url, db_publish_application.describe, db_publish_application.comment, db_publish_application.dingid).filter( db_publish_application.work_number==int(work_number)).all() if task_records: publish_info['task_records'] = task_records[0][:-1] sql_execute= db_sql_execute.query.with_entities(db_sql_execute.host, db_sql_execute.port, db_sql_execute.database, db_sql_execute.sql_url, db_sql_execute.sql_md5, db_sql_execute.describe).filter( db_sql_execute.work_number==int(work_number)).all() if sql_execute: publish_info['sql_execute'] = sql_execute[0] publish_info['reviewer'] = None publish_info['user_info'] = users[task_records[0][-1]] except Exception as e: logging.error(e) return render_template('work_application_details.html', publish_info = publish_info)
Example #16
Source File: root.py From cloudkitty with Apache License 2.0 | 5 votes |
def get_api_versions(): """Returns a list of all existing API versions.""" apis = [ { 'id': 'v1', 'links': [{ 'href': '{scheme}://{host}/v1'.format( scheme=request.scheme, host=request.host, ), }], 'status': 'CURRENT', }, { 'id': 'v2', 'links': [{ 'href': '{scheme}://{host}/v2'.format( scheme=request.scheme, host=request.host, ), }], 'status': 'EXPERIMENTAL', }, ] # v2 api is disabled when using v1 storage if CONF.storage.version < 2: apis = apis[:1] return apis
Example #17
Source File: nsfwaas.py From docker with MIT License | 5 votes |
def where_am_i_from(): protocol = request.environ['wsgi.url_scheme'] hostname = request.host if hostname not in app.config['VALID_HOSTS']: abort(503) g.host = hostname g.protocol = protocol
Example #18
Source File: api_server.py From kytos with MIT License | 5 votes |
def __init__(self, app_name, listen='0.0.0.0', port=8181, napps_manager=None, napps_dir=None): """Start a Flask+SocketIO server. Require controller to get NApps dir and NAppsManager Args: app_name(string): String representing a App Name listen (string): host name used by api server instance port (int): Port number used by api server instance controller(kytos.core.controller): A controller instance. """ dirname = os.path.dirname(os.path.abspath(__file__)) self.napps_manager = napps_manager self.napps_dir = napps_dir self.flask_dir = os.path.join(dirname, '../web-ui') self.log = logging.getLogger(__name__) self.listen = listen self.port = port self.app = Flask(app_name, root_path=self.flask_dir, static_folder="dist", static_url_path="/dist") self.server = SocketIO(self.app, async_mode='threading') self._enable_websocket_rooms() # ENABLE CROSS ORIGIN RESOURCE SHARING CORS(self.app) # Disable trailing slash self.app.url_map.strict_slashes = False # Update web-ui if necessary self.update_web_ui(force=False)
Example #19
Source File: api_server.py From kytos with MIT License | 5 votes |
def shutdown_api(self): """Handle shutdown requests received by Api Server. This method must be called by kytos using the method stop_api_server, otherwise this request will be ignored. """ allowed_host = ['127.0.0.1:'+str(self.port), 'localhost:'+str(self.port)] if request.host not in allowed_host: return "", HTTPStatus.FORBIDDEN.value self.server.stop() return 'Server shutting down...', HTTPStatus.OK.value
Example #20
Source File: application.py From apod-api with Apache License 2.0 | 5 votes |
def home(): return render_template('home.html', version=SERVICE_VERSION, service_url=request.host, methodname=APOD_METHOD_NAME, usage=_usage(joinstr='", "', prestr='"') + '"')
Example #21
Source File: __init__.py From capybara.py with MIT License | 5 votes |
def host(): return "Current host is {0}://{1}".format(request.scheme, request.host)
Example #22
Source File: __init__.py From capybara.py with MIT License | 5 votes |
def redirect_secure(): return flask.redirect("http://{0}/host".format(request.host))
Example #23
Source File: main.py From Remixatron with Apache License 2.0 | 5 votes |
def redirect_https(dir, path): """If this server sits behind a proxy like gunicorn or nginix, then this function will figure that out and re-write the redirect headers accordingly. Args: dir (string): the local directory for the item to return path (string): the file name for the item to return Returns: flask.Response: a Flask Response object """ # Grab the device id. If it hasn't already been set, then create one and set it deviceid = get_userid() if deviceid == None: deviceid = secrets.token_urlsafe(16) # if this server is behind a proxy like ngnix or gunicorn, then we should detect that and # re-write the redirect URL to work correctly. if 'X-Forwarded-Proto' in request.headers and request.headers['X-Forwarded-Proto'] == 'https': url = 'https://' + request.host + url_for(dir, filename=path) resp = redirect(url) resp.set_cookie('deviceid',deviceid, max_age=31536000) resp.headers.add('Cache-Control', 'no-store') return resp # otherwise, just set the device id and redirect as required resp = redirect(url_for(dir, filename=path)) resp.set_cookie('deviceid',deviceid, max_age=31536000) resp.headers.add('Cache-Control', 'no-store') return resp
Example #24
Source File: core.py From swagger-ui-py with Apache License 2.0 | 5 votes |
def _flask_handler(self): from flask import request, jsonify from flask.blueprints import Blueprint swagger_blueprint = Blueprint( 'swagger_blueprint', __name__, url_prefix=self._url_prefix, static_folder=self.static_dir, static_url_path='/' ) @swagger_blueprint.route(r'') def swagger_blueprint_doc_handler(): return self.doc_html @swagger_blueprint.route(r'/') def swagger_blueprint_doc_v2_handler(): return self.doc_html @swagger_blueprint.route(r'/swagger.json') def swagger_blueprint_config_handler(): return jsonify(self.get_config(request.host)) if self._editor: @swagger_blueprint.route(r'/editor') def swagger_blueprint_editor_handler(): return self.editor_html self._app.register_blueprint(swagger_blueprint)
Example #25
Source File: __init__.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def _prepare_flask_request(): # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields url_data = urlparse(request.url) port = url_data.port or (443 if request.scheme == 'https' else 80) return { 'https': 'on' if request.scheme == 'https' else 'off', 'http_host': request.host, 'server_port': port, 'script_name': request.path, 'get_data': request.args.copy(), 'post_data': request.form.copy() }
Example #26
Source File: AntiCSRF.py From xunfeng with GNU General Public License v3.0 | 5 votes |
def anticsrf(f): @wraps(f) def wrapper(*args, **kwargs): try: if request.referrer and request.referrer.replace('http://', '').split('/')[0] == request.host: return f(*args, **kwargs) else: return redirect(url_for('NotFound')) except Exception, e: print e return redirect(url_for('Error'))
Example #27
Source File: views.py From isthislegit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def logout(): ''' Manually override the logout URL to avoid completely signing the user out of all Google accounts ''' if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): return redirect('_ah/logout?continue=https://' + request.host + '/') return redirect(users.create_logout_url('/'))
Example #28
Source File: views.py From fame with GNU General Public License v3.0 | 5 votes |
def prepare_auth_request(request): url_data = urlparse(request.url) return { "https": 'on', 'http_host': request.host, 'server_port': url_data.port, 'script_name': request.path, 'get_data': request.args.copy(), 'post_data': request.form.copy(), # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144 # 'lowercase_urlencoding': True, 'query_string': request.query_string }
Example #29
Source File: api.py From nekoyume with MIT License | 5 votes |
def post_move(): new_move = request.get_json() move = Move.query.get(new_move['id']) if move: return jsonify(result='success') if not move: move = Move.deserialize(new_move) if not move.valid: return jsonify(result='failed', message=f"move {move.id} isn't valid."), 400 db.session.add(move) try: db.session.commit() except IntegrityError: return jsonify(result='failed', message="This node already has this move."), 400 sent_node = Node() if 'sent_node' in new_move: sent_node.url = new_move['sent_node'] move_broadcast.delay( move.id, sent_node_url=sent_node.url, my_node_url=f'{request.scheme}://{request.host}' ) return jsonify(result='success')
Example #30
Source File: core.py From swagger-ui-py with Apache License 2.0 | 5 votes |
def _tornado_handler(self): from tornado.web import RequestHandler, StaticFileHandler interface = self class DocHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.doc_html) class EditorHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.editor_html) class ConfigHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.get_config(self.request.host)) handlers = [ (self._uri(), DocHandler), (self._uri('/'), DocHandler), (self._uri('/swagger.json'), ConfigHandler), (self._uri('/(.+)'), StaticFileHandler, {'path': self.static_dir}), ] if self._editor: handlers.insert(1, (self._uri('/editor'), EditorHandler)) self._app.add_handlers('.*', handlers)