def post(self, id_): """ Publish to BBS """ errors = {} username = self.get_argument("username", "名無し") if username == "": username = "******" mail = self.get_argument("mail") text = self.get_argument("text") if text == "": errors["text"] = True if not errors: session = Session() res = Response(text, username) res.bbs_id = id_ session.add(res) session.commit() session.close() responses = self.get_responses(id_) self.render("BBS/index.html", responses=responses, errors=errors )
async def on_message(self, message): if message.author == self.user: return command_match = self.command_matcher.match(message.content) if (command_match is not None): if (command_match.group(1) == 'strike'): target_user = message.guild.get_member( int(command_match.group(2))) if self.get_next_strike_role(target_user.roles, message.guild.roles) is None: await message.channel.send( '**{} ({})** is at the max strike level.'.format( target_user.display_name, target_user.name)) return session = Session() pending_strike = operations.user_has_pending_strike( session, target_user.id) if pending_strike is not None: await message.channel.send( '**{} ({})** has pending strike.\n{}'.format( target_user.display_name, target_user.name, pending_strike.watched_message_jump_url)) return try: voting_expiration_date = datetime.now() + timedelta( hours=6) bot_message = await message.channel.send( content= '```haskell\n{} ({}) is proposing a strike against {} ({}), react with strike to support\nReason: {}\nVoting ends at {}```' .format( message.author.display_name, message.author.name, target_user.display_name, target_user.name, command_match.group(3), voting_expiration_date.replace(microsecond=0), )) operations.propose_strike( session, message.guild, message.author, target_user, command_match.group(3), bot_message.channel.id, bot_message.id, bot_message.jump_url, voting_expiration_date, ) session.commit() except Exception as e: print(e) session.rollback() finally: session.close()
async def on_guild_join(self, guild): session = Session() try: operations.create_server(session, guild.id) session.commit() except: session.rollback() finally: session.close()
def sample(): title = request.form['title'] # name を受け取る opinion = request.form['opinion'] session = Session() sample = sample_model(id=title) # インスタンスを作成 session.add(sample) # データ追加 session.commit() # データをDBへ反映 session.close() # セッションを閉じる return render_template('sample.html',title = title, opinion = opinion)
def upgrade(self): cnx = connector.connect( host=self.config.host, user=self.config.username, password=self.config.password) db_cursor = cnx.cursor() db_cursor.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{0}'".format(self.config.database)) db_exists = db_cursor.fetchone() if not db_exists: try: db_cursor.execute("CREATE DATABASE {0}".format(self.config.database)) except Exception as ex: message = 'Could not create database: ' + ex.msg logging.error(message) raise Exception(message) cnx.database = self.config.database session = Session(cnx) # do it. session.execute(""" CREATE TABLE IF NOT EXISTS upgrade_history ( id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, upgrade_date DATETIME, version INTEGER )""") session.execute("SELECT IFNULL(MAX(version),0) FROM upgrade_history") db_version = session.fetch_results()[0][0] # first row first col script = self.__create_upgrade_script() max_version = 0 for query in script: if query['version'] > db_version: if query['version'] > max_version: max_version = query['version'] session.execute(query['sql']) if max_version > db_version: session.execute("""INSERT INTO upgrade_history (upgrade_date, version) VALUES('{date}', '{version}');""".format(date=datetime.now().isoformat(), version=max_version)) logginghelper.log_debug('Upgraded database to version ' + str(max_version)) session.commit() session.close()
def post_list_page(): title = request.form['title'] # name を受け取る opinion = request.form['opinion'] session = Session() post_list = post(title=title,opinion=opinion) session.add(post_list) #session.add(opinion_db) session.commit() post_list = session.query( post ).all() session.close() return render_template('post_list.html',post_list=post_list,title=title,opinion=opinion)
def mark_complete_and_release_dependencies(self): # Now let's complete that job. logging.debug('Now completing job: {}, ID: {} (log dir: {})'.format( self.job_name, self.id, self.pipeline.log_directory)) self.status_id = Status.COMPLETE # Find all the jobs depending on the completed job. dependent_jobs = Session.query(Job).filter( Job.depends_on.any(Job.id == self.id)) for j in dependent_jobs: logging.debug('Found dependent job: {0}'.format(j.job_name)) j.depends_on.remove(self) logging.debug( "New dependencies with completed job removed: {0}".format( [x.job_name for x in j.depends_on])) Session.commit()
def __init__(self): """ Write one row to the file_info table, with the schema version and the "started" status False. """ # # Have we been initialized before? If so, schema_version should be # FileInfo.CURRENT_SCHEMA_VERSION. If not, we need to initialize. # logging.debug("In FileInfo constructor. schema_version is: {}.\n" "\t started is {}.".format(self.schema_version, self.started)) if self.schema_version is None: logging.debug("Initializing FileInfo table") self.schema_version = FileInfo.CURRENT_SCHEMA_VERSION self.started = False Session.add(self) Session.commit()
async def on_raw_reaction_add(self, payload): #TODO add this as a customizable user setting PROPONENTS_REQUIRED = 2 if payload.emoji.name == 'strike': session = Session() try: strike = operations.add_strike_proponent( session, payload.message_id, payload.user_id) if strike is not None: if len(strike.proponents) >= PROPONENTS_REQUIRED: guild = self.get_guild(payload.guild_id) target_user = guild.get_member( strike.targeted_user.discord_user_id) strike_level_modified = await self.strike( target_user, guild.roles, strike.reason) strike = operations.mark_strike_operation_successful( session, payload.message_id, strike_level_modified) channel = guild.get_channel(payload.channel_id) discord_proposing_user = guild.get_member( strike.proposing_user.discord_user_id) discord_target_user = guild.get_member( strike.targeted_user.discord_user_id) await channel.send('Strike proposed by **{} ({})** against **{} ({})** was successful. Strike {} applied.'.\ format( discord_proposing_user.display_name, discord_proposing_user.name, discord_target_user.display_name, discord_target_user.name, strike.strike_level_modified ) ) session.commit() except Exception as e: print(e) session.rollback() raise finally: session.close()
class KeyBackend(object): def __init__(self): self.session = Session() if client.get("key") is None: self._key = Fernet.generate_key() client.delete("key") client.set("key", self._key) self.storeKey(self._key) else: self._key = client.get("key") self._fernet = Fernet(self._key) self.sha256 = hashlib.sha256() def storeHash(self, hash, key): data = HashTable(hash_key=key, hash_data_value=hash) self.session.add(data) self.session.commit() def receiveHashKey(self, hash): query = self.session.query(HashTable).filter( HashTable.hash_data_value == hash).first() return query def storeKey(self, key): self.updateKeyStatus() k = KeyTable(key_value=key, key_status=True) self.session.add(k) self.session.commit() def receiveKey(self, key): query = self.session.query(KeyTable).filter( KeyTable.key_value == key, KeyTable.key_status == True).first() return query def updateKeyStatus(self): kTable = self.session.query(KeyTable).filter( KeyTable.key_status == True).first() if kTable is not None: kTable.key_status = False kTable.key_update_date = datetime.datetime.now() self.session.add(kTable) self.session.commit() return True return False @property def fernet(self): return self._fernet @fernet.setter def fernet(self, fernet): self._fernet = fernet @property def key(self): return self._key def keys(self, key): self._key = key self._fernet = Fernet(key)
async def clear_strikes(self): #TODO add this as a customizable user setting TIME_BEFORE_DECAY = 1 session = Session() try: decayed_strikes = operations.get_decayed_strikes( session, TIME_BEFORE_DECAY) for strike in decayed_strikes: guild = self.get_guild(strike.server.discord_server_id) user = guild.get_member(strike.targeted_user.discord_user_id) await self.clear_strike(user, strike.strike_level_modified) strike.decay() await guild.get_channel( strike.watched_message_channel_id ).send('Strike **{}** on {} ({}) has expired.'.format( strike.strike_level_modified, user.display_name, user.name)) session.commit() except Exception as e: print(e) finally: session.close()
def post(self, id_): """ Publish to BBS """ errors = {} username = self.get_argument("username", "名無し") if username == "": username = "******" text = self.get_argument("text") if text == "": errors["text"] = True if not errors: session = Session() res = Response(text, username) res.bbs_id = id_ session.add(res) session.commit() res = res.toDict() session.close() self.set_header("Content-Type", "text/json") self.write(json_encode([res]));
def is_complete(self): """ Check whether all the jobs are complete. If so, mark the pipeline as complete. If any of the jobs have failed, mark it as "Failed" :return: Boolean """ # if we already are marked as Complete, Failed, or Deleted return if self.status_id in [Status.FAILED, Status.COMPLETE, Status.DELETED]: return True # status incomplete_jobs = Session.query(Job). \ filter(Job.status_id != Status.COMPLETE). \ filter(Job.pipeline_id == self.id).all() if not incomplete_jobs: self.status_id = Status.COMPLETE Session.commit() return True # If any are complete, then we have submitted the pipeline. any_submitted = len(incomplete_jobs) < len(self.jobs) any_failed = False for job in incomplete_jobs: if job.is_status('Failed'): logging.debug( "Job {} failed, marking pipeline {} (log dir: {}) failed.". format(job.job_name, self.name, self.log_directory)) self.status_id = Status.FAILED Session.commit() any_failed = True break if job.is_status('Submitted') or job.is_status('Complete'): # If anything is submitted or already complete, but # we're not all complete, then the pipeline is submitted. any_submitted = True if any_failed: for job in self.jobs: if job.status_id == Status.NOT_SUBMITTED: logging.debug( "Marking job {} (log dir: {}) as 'failed pipeline'.". format(job.job_name, self.log_directory)) job.status_id = Status.PIPELINE_FAILURE Session.commit() # A failed pipeline is still considered complete return True if any_submitted and self.status_id != Status.SUBMITTED: logging.debug( "Marking pipeline {} (log dir: {}) submitted.".format( self.name, self.log_directory)) self.status_id = Status.SUBMITTED Session.commit() # But if we get here, we're not complete. return False
def mark_submitted(self, torque_id): logging.debug('Marked submitted: {} (log dir: {})'.format( self.job_name, self.pipeline.log_directory)) self.status_id = Status.SUBMITTED self.torque_id = torque_id Session.commit()
class User(telepot.helper.ChatHandler): def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.ph = PicklesHandler() self.sheets = {} def open(self, initial_msg, seed): content_type, chat_type, chat_id = telepot.glance(initial_msg) try: self.remote_user_id = self.ph.get_userid_from_username(chat_id) except ValueError as ex: print("No user with that id, adding to DB") self.remote_user_id = self.ph.new_user(chat_id) for sheet in self.ph.get_sheets(self.remote_user_id): self.sheets[sheet['name']] = sheet['id'] self.session = Session(chat_id) if self.session.current_sheet_id != None: self.handle_commands(initial_msg['text']) else: self.sender.sendMessage( 'Welcome, {}. You have no sheet open for writing.'.format( chat_id)) return True # prevent on_message() from being called on the initial message def send_user_list_of_their_sheets(self): sheet_names = list(self.sheets.keys()) if len(sheet_names) == 0: self.sender.sendMessage("You have no sheets!") elif len(sheet_names) == 1: self.sender.sendMessage("You have one sheet: {}".format("".join( sheet_names[0]))) else: self.sender.sendMessage("Your sheets are: {}".format( "".join([name + ", " for name in sheet_names[:-1]] + [sheet_names[-1]]))) def on_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) self.handle_commands(msg['text']) def handle_commands(self, msg): command = msg.split(' ')[0] remainder = msg[len(command) + 1:] if command == '/sheets': self.send_user_list_of_their_sheets() elif command == '/open': # if sheet exists then open it up and write each new message as a new element try: if self.session.current_sheet_id != None: self.sender.sendMessage("Closed sheet.") self.session.current_sheet_id = self.sheets[remainder] self.sender.sendMessage( "Opened sheet '{}' for writing.".format(remainder)) except: self.session.current_sheet_id = self.ph.new_sheet( remainder, self.remote_user_id) self.sheets[remainder] = self.session.current_sheet_id self.sender.sendMessage( "Created a sheet called '{}' and opened it for writing.". format(remainder)) elif command == '/close': # close current sheet self.session.current_sheet_id = None elif command == '/delete': # delete a sheet raise NotImplemented elif command == '/show': if remainder in self.sheets.keys(): this_sheet_id = self.sheets[remainder] elif len(remainder) == 0: this_sheet_id = self.session.current_sheet_id else: self.sender.sendMessage("No sheet with that name") elements = self.ph.get_data_in_sheet(this_sheet_id) tl = Timeline("", elements) output_filename = str(int(random.random() * 10**6)) + ".pdf" pdf = pydf.generate_pdf(tl._getHTML()) with open(output_filename, 'wb') as f: f.write(pdf) with open(output_filename, 'rb') as f: self.sender.sendDocument(f) else: # write the message to the currently opened sheet. if self.session.current_sheet_id != None: self.ph.new_element(command + " " + remainder, self.session.current_sheet_id) else: self.sender.sendMessage( "No currently open sheet! Open a sheet for writing with the /open command" ) def on__idle(self, event): self.sender.sendMessage('Idling') self.session.commit() self.close()
def saveEntity(self, entity): session = Session() session.add(entity) session.commit()
def mergeEntity(self, entity): session = Session() session.merge(entity) session.commit()
class BaseHandler(tornado.web.RequestHandler): """A class to collect common handler methods - all other handlers should subclass this one. """ tornado.web.RequestHandler.write_error = error_handler def get_current_user(self): """ Returns the models.User object representing the currently logged in user. The get_current_user will only work if the the user is both logged in and has purchased the film There is also an override for admin accounts """ user = self.get_secure_cookie('user') return self.session.query(User).filter_by(link=user).first() def show_error_message(self, message): self.set_secure_cookie('error_message', message) def show_message(self, message): self.set_secure_cookie('message', message) def login_user(self, user): self.set_secure_cookie('user', user.link) def logout_user(self, user): self.clear_cookie('user') def prepare(self): p3p = 'CP="Like Facebook, Santa does not have a P3P policy -Learn why: http://fb.me/p3p"' self.add_header('Accept-Charset', 'utf-8') self.set_header('P3P', p3p) self.session = Session() def on_finish(self): try: self.session.commit() except Exception as e: self.session.rollback() import traceback logging.critical('Transaction needed to be rolled back because of: \n %s' % traceback.format_exc() ) Session.remove() def respond_with_json(self, success, message, other_info={}): response_object = {'success':success, 'message':message} response_object.update(other_info) self.write(json.dumps(response_object)) return def render_template(self, template, **kwargs): """ An extension to the render() function. This adds things linke message, google analytics key, facebook appid, mixpanel token and the current_user's name to the page at render time. The args parameter allows you to add adhoc variables to a page as well. Remember that the args variable must be accessed like args['vari'] in the tempalte. """ current_user = self.get_current_user() current_user_name = '' current_user_unique_id = '' user_has_purchased = False # Grab the cookie messages cookie_message = self.get_secure_cookie('message') error_message = self.get_secure_cookie('error_message') self.set_secure_cookie("message", '') self.set_secure_cookie("error_message", '') kwargs.update({ 'user':current_user, 'error_message':error_message, 'message':cookie_message, 'facebook_api_key': settings['facebook_api_key'], 'domain':settings['domain'] }) template = 'templates/%s'%template return self.render( template, **kwargs)
def set_started(b): inf = Session.query(FileInfo).one() inf.started = b Session.commit() logging.debug("FileInfo: {}".format(inf)) logging.debug("File is now marked as submitted.")