Python tornado.web() Examples

The following are 30 code examples of tornado.web(). 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 tornado , or try the search function .
Example #1
Source File: __init__.py    From tor_access with MIT License 6 votes vote down vote up
def require(self, **kwargs):
        def actual(handler):
            assert(issubclass(handler, tornado.web.RequestHandler))
            handler.__needcheck__ = kwargs
            category = kwargs.get('category',CATEGORY)
            if not ACL.get(category,None):ACL[category] = {}


            groupnode = kwargs.get('group', None)

            if groupnode:
                """ 分组权限 """
                ACL[category][groupnode.name] = groupnode
                groupnode.append(handler)
                handler.__checkname__ = groupnode.name
            else:
                aclnode = ACLNode(handler)
                ACL[category][aclnode.name] = aclnode
                handler.__checkname__ = aclnode.name
            

            handler.check_access  = check_access
            return handler
    
        return actual 
Example #2
Source File: handlers.py    From doufen with MIT License 6 votes vote down vote up
def get(self, douban_id):
        try:
            subject = db.User.get(db.User.douban_id == douban_id)
            history = db.UserHistorical.select().where(db.UserHistorical.id == subject.id)
        except db.User.DoesNotExist:
            raise tornado.web.HTTPError(404)

        is_follower = db.Follower.select().where(
            db.Follower.follower == subject,
            db.Follower.user == self.get_current_user()
        ).exists()

        is_following = db.Following.select().where(
            db.Following.following_user == subject,
            db.Following.user == self.get_current_user()
        ).exists()

        self.render('user.html', subject=subject, history=history, is_follower=is_follower, is_following=is_following) 
Example #3
Source File: embedding_webagg_sgskip.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, figure):
        self.figure = figure
        self.manager = new_figure_manager_given_figure(id(figure), figure)

        super().__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)',
             tornado.web.StaticFileHandler,
             {'path': FigureManagerWebAgg.get_static_file_path()}),

            # The page that contains all of the pieces
            ('/', self.MainPage),

            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ]) 
Example #4
Source File: demo-chart.py    From stock with Apache License 2.0 6 votes vote down vote up
def __init__(self, figure):
        self.figure = figure
        self.manager = new_figure_manager_given_figure(
            id(figure), figure)

        super(MyApplication, self).__init__([
            # Static files for the CSS and JS
            (r'/_static/(.*)',
             tornado.web.StaticFileHandler,
             {'path': FigureManagerWebAgg.get_static_file_path()}),

            # The page that contains all of the pieces
            ('/', self.MainPage),

            ('/mpl.js', self.MplJs),

            # Sends images and events to the browser, and receives
            # events from the browser
            ('/ws', self.WebSocket),

            # Handles the downloading (i.e., saving) of static images
            (r'/download.([a-z0-9.]+)', self.Download),
        ], debug=True) 
Example #5
Source File: soaphandler.py    From ChatLearner with Apache License 2.0 6 votes vote down vote up
def post(self):
		""" Method post() to process of requests and responses SOAP messages """
		def done(response):
			soapmsg = response.getSoap().toxml()
			self.write(soapmsg)
			self.finish()
		try:
			self._request = self._parseSoap(self.request.body)
			soapaction = self.request.headers['SOAPAction'].replace('"','')
			self.set_header('Content-Type','text/xml')
			for operations in dir(self):
				operation = getattr(self,operations)
				method = ''
				if callable(operation) and hasattr(operation,'_is_operation'):
					num_methods = self._countOperations()
					if hasattr(operation,'_operation') and soapaction.endswith(getattr(operation,'_operation')) and num_methods > 1:
						method = getattr(operation,'_operation') 
						self._executeOperation(operation, done, method=method)
						break
					elif num_methods == 1:
						self._executeOperation(operation, done, method='')
						break
		except Exception as detail:
			fault = soapfault('Error in web service : %s'%detail)
			self.write(fault.getSoap().toxml()) 
Example #6
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, slug: str) -> None:  # type: ignore
        """Render the new paste form, optionally have a lexer preselected from
           the URL."""

        with database.session() as session:
            paste = (
                session.query(database.Paste)
                .filter(database.Paste.slug == slug)
                .first()
            )

            if not paste:
                raise tornado.web.HTTPError(404)

            lexers_available = utility.list_languages()

            await self.render(
                "create.html",
                lexers=["text"],  # XXX make this majority of file lexers?
                lexers_available=lexers_available,
                pagetitle="repaste",
                message=None,
                paste=paste,
            ) 
Example #7
Source File: webservices.py    From ChatLearner with Apache License 2.0 6 votes vote down vote up
def __init__(self,services,object=None,wsdl=None, default_host="", **settings):
		""" Initializes the application for web services

		    Instances of this class are callable and can be passed to
		    HTTPServer of tornado to serve the web services.

		    The constructor for this class takes the name for the web 
		    service (service), the class with the web service (object) 
		    and wsdl with the wsdl file path (if this exist).
		 """
		if isinstance(services,list) and object == None:
			srvs = []
			for s in services:
				srv = s[0]
				obj = s[1]
				srvs.append((r"/"+str(srv),obj))
				srvs.append((r"/"+str(srv)+"/",obj))
			tornado.wsgi.WSGIApplication.__init__(self,srvs,default_host, **settings)
		else:
			self._service = services
			self._object = object
			self._services = [(r"/"+str(self._service),self._object),
					  (r"/"+str(self._service)+"/",self._object),]
			tornado.wsgi.WSGIApplication.__init__(self,self._services,default_host, **settings) 
Example #8
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in the plain."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(file.raw) 
Example #9
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in hex."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(binascii.hexlify(file.raw.encode("latin1"))) 
Example #10
Source File: webservices.py    From ChatLearner with Apache License 2.0 6 votes vote down vote up
def __init__(self,services,object=None,wsdl=None):
		""" Initializes the application for web services

		    Instances of this class are callable and can be passed to
		    HTTPServer of tornado to serve the web services.

		    The constructor for this class takes the name for the web 
		    service (service), the class with the web service (object) 
		    and wsdl with the wsdl file path (if this exist).
		 """
		if isinstance(services,list) and object == None:
			srvs = []
			for s in services:
				srv = s[0]
				obj = s[1]
				dic = s[2]
				srvs.append((r"/" + str(srv), obj, dic))
				srvs.append((r"/" + str(srv) + "/", obj, dic))
			tornado.web.Application.__init__(self, srvs)
		else:
			self._service = services
			self._object = object
			self._services = [(r"/"+str(self._service),self._object),
					  (r"/"+str(self._service)+"/",self._object),]
			tornado.web.Application.__init__(self,self._services) 
Example #11
Source File: backend_webagg.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
            self.url_prefix = kwargs.pop('url_prefix', '')
            return tornado.web.RequestHandler.__init__(self, application,
                                                       request, **kwargs) 
Example #12
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_login_url(self) -> str:
        """Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"] 
Example #13
Source File: backend_webagg.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__(self, url_prefix=''):
        if url_prefix:
            assert url_prefix[0] == '/' and url_prefix[-1] != '/', \
                'url_prefix must start with a "/" and not end with one.'

        super(WebAggApplication, self).__init__(
            [
                # Static files for the CSS and JS
                (url_prefix + r'/_static/(.*)',
                 tornado.web.StaticFileHandler,
                 {'path': core.FigureManagerWebAgg.get_static_file_path()}),

                # An MPL favicon
                (url_prefix + r'/favicon.ico', self.FavIcon),

                # The page that contains all of the pieces
                (url_prefix + r'/([0-9]+)', self.SingleFigurePage,
                 {'url_prefix': url_prefix}),

                # The page that contains all of the figures
                (url_prefix + r'/?', self.AllFiguresPage,
                 {'url_prefix': url_prefix}),

                (url_prefix + r'/mpl.js', self.MplJs),

                # Sends images and events to the browser, and receives
                # events from the browser
                (url_prefix + r'/([0-9]+)/ws', self.WebSocket),

                # Handles the downloading (i.e., saving) of static images
                (url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)',
                 self.Download),
            ],
            template_path=core.FigureManagerWebAgg.get_static_file_path()) 
Example #14
Source File: web.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def get_login_url(self):
        """Override to customize the login URL based on the request.

        By default, we use the 'login_url' application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"] 
Example #15
Source File: demo-chart.py    From stock with Apache License 2.0 5 votes vote down vote up
def create_figure():
    """
    Creates a simple example figure.
    """
    fig = Figure()
    a = fig.add_subplot(111)
    t = np.arange(0.0, 3.0, 0.01)
    s = np.sin(2 * np.pi * t)
    a.plot(t, s)
    return fig


# The following is the content of the web page.  You would normally
# generate this using some sort of template facility in your web
# framework, but here we just use Python string formatting. 
Example #16
Source File: soaphandler.py    From ChatLearner with Apache License 2.0 5 votes vote down vote up
def _countOperations(self):
		""" Private method that counts the operations on the web services """
		c = 0
		for operations in dir(self):
			operation = getattr(self,operations)
			if callable(operation) and hasattr(operation,'_is_operation'):
				c += 1	
		return c 
Example #17
Source File: bookmarks.py    From django-gateone with GNU General Public License v3.0 5 votes vote down vote up
def icon_multifetch(self, urls, response):
        """
        Fetches the icon at the given URLs, stopping when it finds the biggest.
        If an icon is not found, calls itself again with the next icon URL.
        If the icon is found, writes it to the client and finishes the request.
        """
        if response.error:
            if urls:
                url = urls.pop()
                http = tornado.httpclient.AsyncHTTPClient()
                callback = partial(self.icon_multifetch, urls)
                try:
                    http.fetch(url, callback)
                except socket.gaierror:
                    raise tornado.web.HTTPError(404)
            else:
                raise tornado.web.HTTPError(404)
        else:
            if 'Content-Type' in response.headers:
                mimetype = response.headers['Content-Type']
                self.set_header("Content-Type", mimetype)
            else:
                mimetype = "image/vnd.microsoft.icon"
                self.set_header("Content-Type", mimetype)
            data_uri = "data:%s;base64,%s" % (
                mimetype,
                response.body.encode('base64').replace('\n', '')
            )
            self.write(data_uri)
            self.finish() 
Example #18
Source File: wsgi.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, handlers=None, default_host="", **settings):
        web.Application.__init__(self, handlers, default_host, transforms=[],
                                 wsgi=True, **settings) 
Example #19
Source File: wsgi.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, environ, start_response):
        handler = web.Application.__call__(self, HTTPRequest(environ))
        assert handler._finished
        status = str(handler._status_code) + " " + \
            httplib.responses[handler._status_code]
        headers = handler._headers.items()
        if hasattr(handler, "_new_cookie"):
            for cookie in handler._new_cookie.values():
                headers.append(("Set-Cookie", cookie.OutputString(None)))
        start_response(status,
                       [(native_str(k), native_str(v)) for (k, v) in headers])
        return handler._write_buffer 
Example #20
Source File: backend_webagg.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
            self.url_prefix = kwargs.pop('url_prefix', '')
            return tornado.web.RequestHandler.__init__(self, application,
                                                       request, **kwargs) 
Example #21
Source File: controller.py    From teleport with Apache License 2.0 5 votes vote down vote up
def render(self, template_path, **kwargs):
        if self._mode != self.MODE_HTTP:
            log.w('request `{}`, should be web page request.\n'.format(self.request.uri))
            self.write_json(-1, 'should be web page request.')
            return
        self.finish(self.render_string(template_path, **kwargs)) 
Example #22
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_login_url(self) -> str:
        """Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"] 
Example #23
Source File: __init__.py    From tor_access with MIT License 5 votes vote down vote up
def needcheck(**kwargs):
    """
        权限收集的装饰器
        参数说明:
        url : 当url=True 时, 该Handler 需要进行Url 访问限制;
              只有用户权限里有这个Handler标记时,才有权限访问

        ctx_param: 当需要进行内容参数权限控制,多个内容由','分割
                   如: ctx_param = 'project_id,sensor_type',xx?project_id=A&sensor_type=STR;
                   则访问此Handler 时需要判断用户权限表里project_id 存在A 记录, sensor_type 存在STR记录


        group : 将多个Handler 组成一个权限节点来控制

    """
    def actual(handler):
        assert(issubclass(handler, tornado.web.RequestHandler))
        handler.__needcheck__ = kwargs
        groupnode = kwargs.get('group', None)

        if groupnode:
            """ 分组权限 """
            category = groupnode.category or kwargs.get('category',CATEGORY)
            if not ACL.get(category,None):ACL[category] = {}
            ACL[category][groupnode.name] = groupnode
            groupnode.append(handler)
            handler.__checkname__ = groupnode.name
        else:
            category = kwargs.get('category',CATEGORY)
            if not ACL.get(category,None):ACL[category] = {}
            aclnode = ACLNode(handler)
            ACL[category][aclnode.name] = aclnode
            handler.__checkname__ = aclnode.name
        

        handler.check_access  = check_access
        return handler

    return actual 
Example #24
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def write(self, chunk: Union[str, bytes, dict]) -> None:
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the `flush()` method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        ``set_header`` *after* calling ``write()``).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
        https://github.com/facebook/tornado/issues/1009
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish()")
        if not isinstance(chunk, (bytes, unicode_type, dict)):
            message = "write() only accepts bytes, unicode, and dict objects"
            if isinstance(chunk, list):
                message += (
                    ". Lists not accepted for security reasons; see "
                    + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"  # noqa: E501
                )
            raise TypeError(message)
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk) 
Example #25
Source File: wsgi.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(self, application):
        warnings.warn("WSGIAdapter is deprecated, use Tornado's HTTPServer instead",
                      DeprecationWarning)
        if isinstance(application, WSGIApplication):
            self.application = lambda request: web.Application.__call__(
                application, request)
        else:
            self.application = application 
Example #26
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_login_url(self):
        """Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        """
        self.require_setting("login_url", "@tornado.web.authenticated")
        return self.application.settings["login_url"] 
Example #27
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def write(self, chunk):
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the flush() method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        set_header *after* calling write()).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
        https://github.com/facebook/tornado/issues/1009
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish()")
        if not isinstance(chunk, (bytes, unicode_type, dict)):
            message = "write() only accepts bytes, unicode, and dict objects"
            if isinstance(chunk, list):
                message += ". Lists not accepted for security reasons; see " + \
                    "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
            raise TypeError(message)
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk) 
Example #28
Source File: backend_webagg.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
            self.url_prefix = kwargs.pop('url_prefix', '')
            return tornado.web.RequestHandler.__init__(self, application,
                                                       request, **kwargs) 
Example #29
Source File: backend_webagg.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, application, request, **kwargs):
            self.url_prefix = kwargs.pop('url_prefix', '')
            return tornado.web.RequestHandler.__init__(self, application,
                                                       request, **kwargs) 
Example #30
Source File: backend_webagg.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(self, url_prefix=''):
        if url_prefix:
            assert url_prefix[0] == '/' and url_prefix[-1] != '/', \
                'url_prefix must start with a "/" and not end with one.'

        super().__init__(
            [
                # Static files for the CSS and JS
                (url_prefix + r'/_static/(.*)',
                 tornado.web.StaticFileHandler,
                 {'path': core.FigureManagerWebAgg.get_static_file_path()}),

                # An MPL favicon
                (url_prefix + r'/favicon.ico', self.FavIcon),

                # The page that contains all of the pieces
                (url_prefix + r'/([0-9]+)', self.SingleFigurePage,
                 {'url_prefix': url_prefix}),

                # The page that contains all of the figures
                (url_prefix + r'/?', self.AllFiguresPage,
                 {'url_prefix': url_prefix}),

                (url_prefix + r'/js/mpl.js', self.MplJs),

                # Sends images and events to the browser, and receives
                # events from the browser
                (url_prefix + r'/([0-9]+)/ws', self.WebSocket),

                # Handles the downloading (i.e., saving) of static images
                (url_prefix + r'/([0-9]+)/download.([a-z0-9.]+)',
                 self.Download),
            ],
            template_path=core.FigureManagerWebAgg.get_static_file_path())