I have 3 classes in my project. One is a DB class where I have the DB connection for my project, which looks like this.
class DB:
def __init__(self):
self.createConnection()
def createConnection(self):
db = DataBase(
[config.endpoint],
http_auth=(config.username, config.password),
scheme="https"
)
self.__db = db
Now in other classes I want to access and use self.__db How can I use this? My 2nd class is a helper class:
import db
class Helper:
def connection(self):
db = db.createConnection()
self.__db = db
print(self.__db)
i am trying to generate Flask route using a basic DI i.e mapping methods as route handlers, i am a total beginner at Flask so mind my basic skills
class myClass():
def __init__(self):
self.dbConnObj = DbToolsMySql('someconnection', 'slave')
self.dbConnObj.connect()
self.blueprint = Blueprint('myClass', __name__)
self.blueprint.add_url_rule('/my_method', view_func=self.my_method)
def my_method(self, event):
retun "hello"
and then in my handler file
from flask import Flask
from flask_restful import Api, Resource
from src.app.services.myClassimport myClass
app = Flask(__name__)
app.register_blueprint(myClass.blueprint)
if __name__ == "main":
app.run()
Quite simple ehh???? but not working... i am getting following message
Not Found The requested URL was not found on the server. If you
entered the URL manually please check your spelling and try again.
typically you add routes to the Flask app with decorators like so:
app = Flask(__name__)
#app.route('/some-endpoint')
def some_endpoint_handler():
# do something
pass
Or you can add without a decorator like so:
def some_endpoint_handler():
# do something
pass
app = Flask(__name__)
app.route('/some-endpoint', methods=['GET'])(some_endpoint_handler)
So in your scenario, you can pass the app.route call to your myClass object and set the route like this:
class myClass():
def __init__(self, router):
self.dbConnObj = DbToolsMySql('someconnection', 'slave')
self.dbConnObj.connect()
self.blueprint = Blueprint('myClass', __name__)
#self.blueprint.add_url_rule('/my_method', view_func=self.my_method)
router('/my_method', ['GET'])(self.my_method)
def my_method(self, event):
retun "hello"
myObj = myClass( app.route )
or, invert the dependency:
app = Flask(__name__)
#app.route(myClass.blueprint.some_endpoint_string)
def some_endpoint_handler():
myClass.blueprint.call_some_endpoint_handler()
pass
if __name__ == "main":
app.run()
I am new to Python and MongoDB environment. I am implementing a small application in Python with Tornado + MongoDB. I want to store sessions in mongoDB.
In server.py
import os
import tornado.web
import tornado.ioloop
import settings
application = tornado.web.Application(
settings.urls,
my_template_path,
my_static_path
)
if __nam__ == '__main__':
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
In settings.py
import handler as H
urls = [
(r"/", H.ShowHome),
(r"/login", H.ShowLogin),
(r"/dashboard", H.ShowDashboard)
]
In handler.py
import os
# import session or some library ????
class ShowHome(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.SESSION = True or False based on session cookie
def get(self):
if not self.SESSION:
self.redirect('/login')
else:
self.render('index.html')
class ShowLogin(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.SESSION = True or False based on session cookie
def get(self):
if self.SESSION:
self.redirect('/dashboard')
else:
self.render('login.html')
class ShowDashboard(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.session = True or False based on session cookie
def get(self):
if not SESSION:
self.redirect('/login')
else:
self.render('dashboard.html')
In handlers I want to check session, how do I do this?
Do you mean something like this?
class Base(tornado.web.RequestHandler):
def get_unique_id(self):
return self.get_secure_cookie('unique_id')
def set_unique_id(self, some_value):
return self.set_secure_cookie('unique_id', some_value)
class ShowLogin(Base):
def get(self):
if get_unique_id():
# Get stuff from Mongo using unique_id
# mongo calls
self.redirect('/dashboard')
else:
self.render('login.html')
class LoginLogin(Base):
def post(self):
self.set_unique_id(some_id)
You probably dont want to do this though - Let Tornado handle if someone is logged in or out with the authenticated decorator
And unless you are holding a lot of data or very sensitive data it's normal (and easier) to put session data in the cookies
I'm new to Tornado, and I'm currently trying to get past this recent stumbling block. Currently I have some database variables defined, and I instantiate the handlers, settings, and database connection info when I init the Application class. I also have a base handler class (named BaseHandler) which provides a simple database interface to other classes. I'd like to split some of my classes into other files, and have most of my database logic in those other class methods, and keep application.py for the routes, and instantiating these other classes when needed, and passing the necessary data to them for the database. How would I access this self.db function from within these other files/classes?
application.py:
import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from user import User
# Define some startup settings, can be changed through the command line
define("port", default=8888, help="Run on the given HTTP port", type=int)
define("db_host", default="localhost:3306", help="Database host")
define("db_name", default="database_name", help="Database name")
define("db_user", default="user", help="Database username")
define("db_pass", default="password", help="Database password")
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler)
]
settings = dict(
application_title = u"Test Application",
template_path = os.path.join(os.path.dirname(__file__), "templates"),
static_path = os.path.join(os.path.dirname(__file__), "static"),
autoescape = None
)
tornado.web.Application.__init__(self, handlers, **settings)
self.db = tornado.database.Connection(
host=options.db_host, database=options.db_name,
user=options.db_user, password=options.db_pass)
class BaseHandler(tornado.web.RequestHandler):
#property
def db(self):
return self.application.db
class MainHandler(BaseHandler):
def get(self):
u = User()
self.write(tornado.escape.json_encode(u.get_user("test#test.com)))
user.py:
class User(object):
def get_user(self, email):
result = self.db.get("SELECT first_name, last_name FROM users WHERE email = %s", email)
if not result: return False
return True, result
This logic does work fine when I haven't separated the logic out to a separate file, so I'm clearly doing something wrong/missing something.
I meet the same situation just now, then I view some examples on github and made that.
I separate my files like:
server.py: run app
urls.py: define handers and ui_modules
da.py: define helpful methods for data access
Following are some brief of each file, I think this can help you to solve your problem.
urls.py
import main
import topic
handlers=[]
handlers.extend(main.handlers)
handlers.extend(topic.handlers)
ui_modules={}
da.py
import tornado.database
from tornado.options import define,options
define("mysql_host", default="127.0.0.1:3306", help="database host")
define("mysql_database", default="forum", help="database name")
define("mysql_user", default="root", help="database user")
define("mysql_password", default="111111", help="database password")
db = tornado.database.Connection(
host=options.mysql_host, database=options.mysql_database,
user=options.mysql_user, password=options.mysql_password)
server.py
import os
import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
import da
class Application(tornado.web.Application):
def __init__(self):
from urls import handlers,ui_modules
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
login_url="/signin",
ui_modules=ui_modules,
debug=True,
)
super(Application,self).__init__(handlers,**settings)
# tornado.web.Application.__init__(self, handlers, **settings)
# Have one global connection to the blog DB across all handlers
self.db = da.db
def runserver():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
runserver()
You can use db just 'from da import *' and then everything goes well, or you can write a BaseHandler extends tornado.web.RequestHandler and define a property:
class BaseHandler(tornado.web.RequestHandler):
#property
def db(self):
return self.application.db
Every handler that extends BaseHandler can use self.db to do database operations then.
How would I go about implementing the MainPage class?
import cgi
import os
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model): #setting up database
a = db.StringProperty(multiline=True)
b = db.StringProperty(multiline=True)
c = db.StringProperty(multiline=True)
d = db.StringProperty(multiline=True)
class MainPage(webapp.RequestHandler):
def get(self):
##I want to access the content of the database here which is defined in Downloader class.
##For example let the value of greeting.a be assigned to alpha variable.
#Entering data to the database
class Downloader(webapp.RequestHandler):
def get(self):
greeting=Greeting()
greeting.a=self.request.GET.get('a')
greeting.b=self.request.GET.get('b')
greeting.c=self.request.GET.get('c')
greeting.d=self.request.GET.get('d')
greeting.put()
You could pass a Downloader object to MainPage on initialization:
class MainPage(webapp.RequestHandler):
def __init__(self, downloader):
self.downloader = downloader
def get(self):
self.downloader.get()
This is solved by basically naming the database, and refer to it from another class