def show_info(): app = powlib.load_class( "App", "App") app_versions = powlib.load_class( "Version", "Version") sess = app.pbo.getSession() app = sess.query(App.App).first() print "showing migration information for" #print " -- Appname: " + app.name print " -- currentversion is : " + str(app.currentversion) print " -- max version is : " + str(app.maxversion)
def update_app_and_version(maxversion, filename, version, comment=""): """ update the app table with the new version update the version table with: filename, version and comment (if any). """ app = powlib.load_class( "App", "App") app_versions = powlib.load_class( "Version", "Version") app = app.find_first() app.maxversion = str(maxversion) app.update() app_versions.filename = str(filename) app_versions.version = str(version) app_versions.comment = str(comment) app_versions.update() return
def belongs_to(self,rel_table): """ Description: Creates the foreign_key for the table relation. Remark: The old table is dropped. input parameters: rel_table (type:string) Name of the table to be related. """ # # Now creating the foreign_key # fkey = powlib.pluralize(rel_table) + ".id" if fkey in self.__table__.foreign_keys: err_msg = " already has a belongs_to relation to table " print "Table ", self.__table__.name, err_msg , rel_table raise StandardError( "Table " + self.__table__.name + err_msg + rel_table) else: fkey = "" #cons = ForeignKeyConstraint([table.c.fkey], [othertable.c.id]) modelname = string.capitalize(rel_table) #print " -- loading model: ", modelname rel_model = powlib.load_class(modelname, modelname) #col = rel_model.getColumn(self.__table__.name + "_id") #print rel_model.getColumns() #print str(CreateTable(rel_model.__table__)) self.__table__.append_column(Column(rel_model.__table__.name + "_id", Integer, ForeignKey(rel_model.__table__.name +".id"))) cts = str(CreateTable(self.__table__)) create_table_ddl = DDL(cts) print cts self.__table__.drop() self.pbo.getConnection().execute(create_table_ddl) return
def do_erase(): app = powlib.load_class("App", "App") app_version = powlib.load_class("Version", "Version") sess = app.pbo.getSession() app = sess.query(App.App).first() print " -- erasing migration version:", str(app.maxversion) sess.add(app) maxversion = int(app.maxversion) currversion = int(app.currentversion) # # only delete a migration file if it is not in use #(so the current mig is not baed on it) # if maxversion == currversion: print "cannot delete the currently active migration version. ", print " Migrate down first" return # get the version-info from app.db.version ver = app_version.find_by("version", maxversion) #sess.add(ver) filename = ver.filename + ".py" filename_pyc = filename + "c" print "attempting to delete version: " + str(maxversion) + "->" + filename if os.path.isfile(os.path.normpath("./migrations/" + filename)): os.remove(os.path.normpath("./migrations/" + filename)) print " -- deleted: ", filename if os.path.isfile(os.path.normpath("./migrations/" + filename_pyc)): os.remove(os.path.normpath("./migrations/" + filename_pyc)) print " -- deleted: ", filename_pyc # delete the app.db.version entry ver.delete() maxversion -= 1 print "setting new currentversion to: " + str(currversion) app.maxversion = maxversion print "setting new maxversion to: " + str(maxversion) #sess.dirty sess.commit()
def set_currentversion( ver ): print "migrating " app = powlib.load_class( "App", "App") app_versions = powlib.load_class( "Version", "Version") sess = app.pbo.getSession() app = sess.query(App.App).first() #print app #print "name: " + app.name #print "path: " + app.path print " -- currentversion: " + str(app.currentversion) print " -- setting currentversion to: " + str(ver) #print "maxversion: " + str(app.maxversion) goalversion = int(ver) if goalversion >=0 and goalversion <=app.maxversion: app.currentversion = ver else: print " -- ERROR: new currentversion <=0 or >= maxversion" return sess.commit() return
def drop_table(tablename, **kwargs): model = PowTable.PowTable() modelname = powlib.table_to_model(tablename) model = powlib.load_class( modelname, modelname ) #print type(model) #powlib.print_sorted(dir(model)) if not "checkfirst" in kwargs: kwargs["checkfirst"]="False" print " -- set checkfirst=", kwargs["checkfirst"] model.__table__.drop( **kwargs ) print " -- dropped table: ", tablename return
def get_new_version(): """ Constructs the new version by queriing the App Table for maxversion """ app = powlib.load_class( "App", "App") sess = app.pbo.getSession() app = sess.query(App.App).first() version = app.maxversion version += 1 return version
def re_route(self, controller, action,**kwargs): """ Loads another Controller and calls the given action""" kwargs["template"] = pow.global_conf["DEFAULT_TEMPLATE"] controller = None controller = powlib.load_class( string.capitalize(controller),string.capitalize(controller)) if controller != None: if hasattr( aclass, action ): controller.setCurrentAction(action) real_action = eval("controller." + action) return real_action(kwargs["powdict"]) else: return render_message("Error, no such action: %s, for controller: %s" % (action, controller), "error", **kwargs) else: return render_message("Error, no such controller: %s" % (controller), "error", **kwargs) return render_message("Error, this should never be reached" % (controller), "error", **kwargs)
def smart_form_input( modelname = None, colname = None, value = "", accept = "", options_dict = None ): """ Generates the right form input for the given model.column type. Basically: default, text and VArchar => <input type=text binary and blob => <input type=file Text => <textarea """ colname = string.lower(colname) input_first = '<label for="%s">%s:</label>' % (colname, colname) if modelname == None: # No model given, so always generate a standard text type or the given type input html field if type == None: input_first += "<input type='text' name='%s' value='%s'>" % (colname, value) else: input_first += "<input type='%s' name='%s' value='%s'>" % (type, colname, value) else: # model given, so create the right input-type according to the models datatype # the field is the same as the given name. So type of model.name determines the input-type mod = powlib.load_class(string.capitalize(modelname), string.capitalize(modelname)) statement = 'type(mod.__table__.columns["%s"].type)' % (colname) curr_type = eval(statement) print curr_type if curr_type == type(sqlalchemy.types.INTEGER()) or curr_type == type(sqlalchemy.types.VARCHAR()): input_first += "<input type='text' name='%s' value='%s'>" % (colname, value) elif curr_type == type(sqlalchemy.types.TEXT()): input_first += '<textarea name="%s" class="input-xxlarge" rows="15">%s</textarea>' % (colname, value) elif curr_type == type(sqlalchemy.types.BLOB()) or curr_type == type(sqlalchemy.types.BINARY()): if string.lower(colname) == pow.global_conf["DEFAULT_IMAGE_NAME"]: input_first += '<input name="%s" type="file" size="50" maxlength="%s" accept="image/*">' % (colname, pow.global_conf["MAX_FILE_UPLOAD"]) elif string.lower(colname) == pow.global_conf["DEFAULT_VIDEO_NAME"]: input_first += '<input name="%s" type="file" size="50" maxlength="%s" accept="video/*">' % (colname, pow.global_conf["MAX_FILE_UPLOAD"]) elif string.lower(colname) == pow.global_conf["DEFAULT_AUDIO_NAME"]: input_first += '<input name="%s" type="file" size="50" maxlength="%s" accept="audio/*">' % (colname, pow.global_conf["MAX_FILE_UPLOAD"]) elif string.lower(colname) == pow.global_conf["DEFAULT_TEXT_NAME"]: input_first += '<input name="%s" type="file" size="50" maxlength="%s" accept="text/*">' % (colname, pow.global_conf["MAX_FILE_UPLOAD"]) else: input_first += "<ERROR in smart_form_input()>" return input_first
def __init__(self): self.mylookup = TemplateLookup(directories=[os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/")), os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/layouts/")), os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/stylesheets/")) ] ) # example how to instanciate the model: if self.modelname == None or self.modelname == "None": self.model = None self.session = None else: self.model = powlib.load_class(self.modelname, self.modelname) self.session = self.model.pbo.getSession() # put the actions that require a login into login_required list. self.login_required = [] # put the actions you implemented but do not want to be callable via web request # into the locked_actions list self.locked_actions = [] self.current_action = "NOT_DEFINED"
def do_job(options, filename, method): print "migrating" #print options # get rid of trailing directories h,t = os.path.split(filename) # get rid of file extensions filename, ext = os.path.splitext(t) #print filename # load the class mig = powlib.load_class( filename, "Migration" ) # execute the up() method if method != "None": eval("mig." + str(method) + "()") elif options.direction == "up": mig.up() elif options.direction == "down": mig.down() else: raise StandardError("Migration Direction is neither <up> nor <down>.") return
def __init__(self): # put the actions that require a login into login_required list. self.login_required = [] # put the actions you implemented but do not want to be callable via web request # into the locked_actions dictionary. Format: "actionname" : "redirect_to" } # simple_server and pow_router will not call locked actions but redirect to the given value, instead self.locked_actions = {} self.current_action = "NOT_DEFINED" # Format: { filter: ( selector, [list of actions] ) } self.pre_filter_dict = {} self.mylookup = TemplateLookup(directories=[os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/")), os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/layouts/")), os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)),"../views/stylesheets/")) ] ) # example how to instanciate the model: if self.modelname == None or self.modelname == "None": self.model = None self.session = None else: self.model = powlib.load_class(self.modelname, self.modelname) self.session = self.model.pbo.getSession()
def render_migration(name, model, comment, col_defs = "", PARTS_DIR = powlib.PARTS_DIR, prefix_dir = "./"): # #print "generate_migration: " + name + " for model: " + model # # add the auto generated (but can be safely edited) warning to the outputfile infile = open (os.path.normpath(PARTS_DIR + "/can_be_edited.txt"), "r") ostr = infile.read() infile.close() # add a creation date ostr = ostr + os.linesep ostr = ostr + "# date created: \t" + str(datetime.date.today()) ostr = ostr + os.linesep # Add the model_stub part1 content to the newly generated file. infile = open (os.path.normpath( PARTS_DIR + "db_migration_stub2_part1.py"), "r") ostr = ostr + infile.read() infile.close() pluralname = powlib.plural(model) ostr += powlib.tab + "table_name=\"" + pluralname + "\"" ostr += powlib.linesep #print "modelname was: " + model + " pluralized table_name is:" + pluralname # Add the model_stub part2 content to the newly generated file. infile = open (os.path.normpath( PARTS_DIR + "db_migration_stub2_part2.py"), "r") ostr = ostr + infile.read() infile.close() # # Add / Replace the column definitions with the given ones by -d (if there were any) # if col_defs != "None": ostr = transform_col_defs( ostr, col_defs ) app = powlib.load_class( "App", "App") app_versions = powlib.load_class( "Version", "Version") sess = app.pbo.getSession() app = sess.query(App.App).first() version = app.maxversion oldmaxversion = version version += 1 verstring = powlib.version_to_string(version) print "generate_migration: " + name + " for model: " + model #print "version: " + str(version) #print "version2string: " + verstring filename = os.path.normpath ( "./migrations/" + verstring +"_" + name +".py" ) #update the app table with the new version #appTable.update().values(maxversion= str(version) ).execute() app.maxversion = str(version) app.update() app_versions.filename = str(verstring +"_" + name ) app_versions.version = str(version) app_versions.comment = str(comment) app_versions.update() print " -- maxversion (old,new): (" + str(oldmaxversion) + "," + str(app.maxversion) +")" ofile = open( os.path.normpath(os.path.join(prefix_dir,filename)) , "w+") print " -- created file:" + str(os.path.normpath(os.path.join(prefix_dir,filename))) ofile.write( ostr ) ofile.close() return
def do_migrate( goalversion, direction): #powlib.load_module("App") print "..migrating " app = powlib.load_class( "App", "App") app_versions = powlib.load_class( "Version", "Version") sess = app.pbo.getSession() app = sess.query(App.App).first() #print app #print "name: " + app.name #print "path: " + app.path print " -- currentversion: " + str(app.currentversion) #print "maxversion: " + str(app.maxversion) currentversion = int(app.currentversion) maxversion = int(app.maxversion) times = 1 if goalversion == None: pass elif goalversion > maxversion: print " -- Error: version would become greater than Maxversion.. bailing out" return else: print " -- migrating to version:" + str(goalversion) # setting number of times to run if goalversion < currentversion: direction = "down" times = currentversion - goalversion elif goalversion >= currentversion: direction = "up" times = goalversion - currentversion else: times = 0 print " -- Running " + str(times) + " times: " sess.add(app) if goalversion < 2 and goalversion != None: #then the App or versions table would be migrated down which will break the environment. print " -- Error: you are attemting to migrate down the sytem tables version and/or App.. bailing out" return for run in range(0,times): # # migrate up if direction == "up": if currentversion > maxversion: print " -- Error: version would become greater than Maxversion.. bailing out" return currentversion += 1 ver = app_versions.find_by("version", currentversion) #filename = os.path.normpath ( powlib.version_to_string(currentversion) +"_" + "migration" ) filename = ver.filename mig = powlib.load_class( filename, "Migration" ) mig.up() print '{0:18} ==> {1:5} ==> {2:30}'.format(" -- Migration run #", str(run+1).zfill(3), filename) # # migrate down # elif direction == "down": if currentversion <= 0: print " -- Error: version would become less than < 0 .. bailing out" return #filename = os.path.normpath ( powlib.version_to_string(currentversion) +"_" + "migration" ) ver = app_versions.find_by("version", currentversion) filename = ver.filename mig = powlib.load_class( filename, "Migration" ) mig.down() currentversion -= 1 print '{0:18} ==> {1:5} ==> {2:20}'.format(" -- Migration run", str(run+1).zfill(5), filename) else: raise StandardError("Direction must be either up or down") print " -- setting currentversion to: " + str(currentversion) app.currentversion = currentversion #sess.dirty sess.commit() return
def setup_properties(self): for elem in self.properties_list: modelname = string.capitalize(powlib.singularize(elem)) rel_model = powlib.load_class(modelname, modelname) self.__mapper__.add_properties({ elem : relationship(rel_model.__mapper__) })
def render_migration(name, model, comment): # #print "generate_migration: " + name + " for model: " + model # add the auto generated warning to the outputfile infile = open (os.path.normpath(PARTS_DIR + "/can_be_edited.txt"), "r") ostr = infile.read() infile.close() # add a creation date ostr = ostr + os.linesep ostr = ostr + "# date created: \t" + str(datetime.date.today()) ostr = ostr + os.linesep # Add the model_stub part1 content to the newly generated file. infile = open (os.path.normpath( PARTS_DIR + "db_migration_stub2_part1.py"), "r") ostr = ostr + infile.read() infile.close() pluralname = powlib.plural(model) ostr += powlib.tab + "table_name=\"" + pluralname + "\"" ostr += powlib.linesep #print "modelname was: " + model + " pluralized table_name is:" + pluralname # Add the model_stub part2 content to the newly generated file. infile = open (os.path.normpath( PARTS_DIR + "db_migration_stub2_part2.py"), "r") ostr = ostr + infile.read() infile.close() #ostr += powlib.tab + powlib.tab + powlib.tab + "Column('id', Integer, Sequence('" + model +"_id_seq'), primary_key=True)," #ostr += powlib.newline app = powlib.load_class( "Appinfo", "Appinfo") app_versions = powlib.load_class( "Version", "Version") sess = app.pbo.getSession() app = sess.query(Appinfo.Appinfo).first() version = app.maxversion oldmaxversion = version version += 1 verstring = powlib.version_to_string(version) print "generate_migration: " + name + " for model: " + model #print "version: " + str(version) #print "version2string: " + verstring filename = os.path.normpath ( "./migrations/" + verstring +"_" + name +".py" ) #update the app table with the new version #appTable.update().values(maxversion= str(version) ).execute() app.maxversion = str(version) app.update() app_versions.filename = str(verstring +"_" + name ) app_versions.version = str(version) app_versions.comment = str(comment) app_versions.update() print " -- maxversion (old,new): (" + str(oldmaxversion) + "," + str(app.maxversion) +")" ofile = open( filename , "w+") print " -- created file:" + str(filename) ofile.write( ostr ) ofile.close() return
def powapp_simple_server(environ, start_response): #print show_environ_cli(environ) output = [] powdict = {} real_action = None req = Request(environ) req.charset = pow.global_conf["DEFAULT_ENCODING"] #print "webob: req.params", req.params #print "webob: req.body", req.body #print dir(req.params) # # relevant parameters have to be defined here # (Same as for apache the declarations in the httpd.conf file # # redirect static media from the meta link static to the real source dir # advantage is: you can alway refer safely to /static/<something> inside your css o .tmpl # files and the real source can be anywhere. sometimes the real static source differs from # prod-webserver A to prod-webserver B. with this litte tirck you can leave your links unchanged. # for apache the redirection is done in http.conf alias_dict ={ "/static/css/" : "./public/css/", "/static/stylesheets/" : "./public/css/", "/static/scripts/" : "./public/js/", "/static/js/" : "./public/js/", "/static/documents/" : "./public/doc/", "/static/doc/" : "./public/doc/", "/static/ico/" : "./public/ico/", "/static/img/" : "./public/img/" } environ["SCRIPT_FILENAME"] = __file__ powdict["POW_APP_NAME"] = "atest" powdict["POW_APP_URL"] = "www.pythononwheels.org" powdict["POW_APP_DIR"] = environ.get("pow.wsgi_dir") powdict["ERROR_INFO"] = "NONE" # Get the session object from the environ session = environ['beaker.session'] #TO_DO: set the right status in the end, according to the situatio instead of setting it hard-coded here status = '200 OK' response_headers = [ #('Content-type', 'text/html; charset=utf-8') ('Content-type', 'text/html') ] if not session.has_key('user.id'): session['user.id'] = 0 #session.save() powdict["SESSION"] = session print "-- request info:" print "-- webob: req.content_type: ", req.content_type print "-- webob: ", req.method powdict["REQ_CONTENT_TYPE"] = req.content_type powdict["REQ_PARAMETERS"] = req.params powdict["REQ_BODY"] = req.body print powdict["REQ_PARAMETERS"] if MODE > MODE_NORMAL: print plist print plist.keys() plist = req.params #if plist.has_key("image"): # print "Image found: ", plist['image'].filename # ofile = file(plist['image'].filename, "wb") # infile = plist['image'].file # ofile.write( infile.read() ) # #ofile.write( plist["image"].value ) # ofile.close() # # handling static files # pinfo = environ.get("PATH_INFO") pinfo_before = pinfo ostr = "" # # check for static links and replace them when found. # found_static = False for elem in alias_dict: if string.find(pinfo, elem) != -1: found_static = True pinfo = string.replace(pinfo,elem, alias_dict[elem]) environ["PATH_INFO"] = pinfo if found_static == True: print "-- Static REQUEST --------------------------------------------------------- " non_binary = [".css", ".html",".js",".tmpl"] ctype = "UNINITIALIZED" ftype = os.path.splitext(pinfo)[1] if string.lower(ftype) in non_binary: infile = open (os.path.normpath(pinfo), "r") else: infile = open (os.path.normpath(pinfo), "rb") ostr = infile.read() infile.close() #print "file type is: ", ftype, " -> ", ctype if string.lower(ftype) == ".gif": ctype = "image/gif" elif string.lower(ftype) == ".jpg" or string.lower(ftype) ==".jpeg": ctype= "image/jpeg" elif string.lower(ftype) == ".css": ctype = "text/css" elif string.lower(ftype) == ".png": ctype = "image/png" elif string.lower(ftype) ==".js": ctype= "application/x-javascript" else: ctype = "text/html" #print "file type is: ", ftype, " responding with type-> ", ctype response_headers = [ ('Content-type', ctype ) ] start_response(status, response_headers) return [ostr] print "-- Dynamic REQUEST --------------------------------------------------------- " if MODE > MODE_INFO : print "Request: " + environ["REQUEST_METHOD"] + " " + environ["PATH_INFO"] + " " + environ["SERVER_PROTOCOL"] + " " + environ["QUERY_STRING"] print "PATH_INFO before: ", pinfo_before print "PATH_INFO after: ", pinfo if not session.has_key('counter'): session['counter'] = 0 else: session['counter'] += 1 powdict["SCRIPT_FILENAME"] = environ.get("SCRIPT_FILENAME") powdict["SCRIPT_DIR"] = os.path.dirname(environ.get("SCRIPT_FILENAME")) powdict["SCRIPT_VIEWS_DIR"] = os.path.abspath(os.path.join(os.path.dirname(environ.get("SCRIPT_FILENAME")) + "/views/")) # PATH_INFO contains the path beginning from the app-root url. # first part is the controller, # second part is the action powdict["PATH_INFO"] = environ.get("PATH_INFO") #print os.path.split(powdict["PATH_INFO"]) powdict["ENVIRON"] = pow_web_lib.show_environ( environ ) powdict["DOCUMENT_ROOT"] = environ.get("DOCUMENT_ROOT") powdict["FLASHTEXT"] = "" powdict["FLASHTYPE"] ="error" #output.append( show_environ( output, environ ) ) # # get controller and action # print "environ[\"PATH_INFO\"] = ", environ["PATH_INFO"] pathdict = pow_web_lib.get_controller_and_action(environ["PATH_INFO"]) #(controller,action) = os.path.split(pathinfo) print "(controller,action) -> ", pathdict controller = powdict["CONTROLLER"] = pathdict["controller"] action = powdict["ACTION"] = pathdict["action"] powdict["PATHDICT"]=pathdict #TO_DO: include the real, mod re based routing instead of seting it hard to user/list here. if controller == "": defroute = pow.routes["default"] #defroute = powlib.readconfig("pow.cfg","routes","default") print pow_web_lib.get_controller_and_action(defroute) pathdict = pow_web_lib.get_controller_and_action(defroute) #(controller,action) = os.path.split(pathinfo) print "(controller,action) -> ", pathdict controller = powdict["CONTROLLER"] = pathdict["controller"] action = powdict["ACTION"] = pathdict["action"] powdict["PATHDICT"]=pathdict print "Using the DEFAULT_ROUTE: ", print "(controller,action) -> ", pathdict # get rid of the first / in front of the controller. string[1:] returns the string from char1 to len(string) controller = string.capitalize(controller) + "Controller" # # route the request # #print "Loading Class:", controller aclass = powlib.load_class(controller,controller) #print "setting Action: ", action aclass.setCurrentAction(action) #output.append(action + "<br>") # checking if action is locked if aclass.is_locked(action): # locked, so set the action to the given redirection and execute that instead. # TODO: Could be aditionally coupled with a flashtext. print "Action: ", action, " locked." cont, action = aclass.get_redirection_if_locked(action) if cont != None and cont != "None" and cont != "": controller = string.capitalize(cont) + "Controller" aclass = powlib.load_class(controller,controller) aclass.setCurrentAction(action) print " -- Redirecting to: ", action # # Now really execute the action # if hasattr( aclass, action ): real_action = eval("aclass." + action) output.append(real_action(powdict).encode(pow.global_conf["DEFAULT_ENCODING"])) else: msg = "ERROR: No such class or action %s.%s " % (controller, action) output.append(msg) # # error handling wsgi see: http://www.python.org/dev/peps/pep-0333/#error-handling # start_response(status, response_headers) return output