def form_entity(type, id=None): session = Session() entity = None tag_ids = None if id != None: entity = session.query(Entity).filter(Entity.id == id).first() tag_ids = [ tag.id for tag in entity.tags ] files = None series = None soundtracks = None if(type == 'song'): files = session.query(File).filter(File.type == 'song').all() series = session.query(Series).filter(or_(Series.type == 'album', Series.type == 'soundtrack')).all() if(type == 'book'): files = session.query(File).filter(File.type == 'book').all() series = session.query(Series).filter(Series.type == 'book_series').all() if(type == 'movie'): series = session.query(Series).filter(Series.type == 'movie_series').all() soundtracks = session.query(Series).filter(Series.type == 'soundtrack').all() covers = session.query(File).filter(File.type == 'image').all() keywords = session.query(Tag).filter(Tag.type == 'keyword').all() genres = session.query(Tag).filter(Tag.type == 'genres').all() rendered = render_template("form_entity.html", type=type, entity=entity, covers=covers, files=files, series=series, soundtracks=soundtracks, keywords=keywords, genres=genres, tag_ids=tag_ids) session.commit() return rendered
def submit_person(): session = Session() person = None if 'id' in request.form: person = session.query(Person).filter(Person.id == request.form['id']).first() else: person = Person() person.name = request.form['name'] if 'location' in request.form: person.location = request.form['location'] if 'image_id' in request.form and request.form['image_id']: person.image_id = request.form['image_id'] elif('cover' in request.files) and request.files['cover'] and request.files['cover'].filename: upload = request.files['cover'] file = File() file.name = secure_filename(upload.filename) file.type = 'image' file.mime = guess_type(file.name)[0] file.data = upload.read() person.image = file session.add(person) session.commit() return redirect(url_for('index'))
def num_songs_queued(): """Returns the number of songs that are queued""" session = Session() num_songs = session.query(Packet).filter_by( player_name=PLAYER_NAME).count() session.commit() return num_songs
def play_next(self, skip=False): if self.empty(): random_song = random_songs(1)['results'] if len(random_song) == 1: self.vote_song('RANDOM', random_song[0]['id']) if not self.empty(): if player.now_playing: if isinstance(player.now_playing, YouTubeVideo): self.remove_video(player.now_playing.url, skip=skip) else: self.remove_song(player.now_playing.id, skip=skip) session = Session() next_packet = session.query(Packet).order_by(Packet.finish_time).first() if next_packet: if next_packet.video_url: video = YouTubeVideo(next_packet) player.play_media(video) session.commit() return video.dictify() else: next_song = session.query(Song).get(next_packet.song_id) player.play_media(next_song) next_song.history.append(PlayHistory(user=next_packet.user)) session.commit() return next_song.dictify()
def add(self, message, latitude, longitude, time_limit=60): post = Post(message, latitude, longitude, time_limit) session = Session() session.add(post) session.commit() session.close() return post
def _initialize_virtual_time(self): """Initializes virtual time to the latest packet arrival time""" session = Session() last_arrived_packet = session.query(Packet).order_by(Packet.arrival_time.desc()).first() if last_arrived_packet: self.virtual_time = last_arrived_packet.arrival_time session.commit()
def _prune_dir(path, prune_modified=False): """Prunes songs in directory and returns set of remaining songs.""" session = Session() songs = session.query(Song).filter(Song.path.like(path + '%')).all() remaining_paths = set() for song in songs: if not isfile(song.path): session.delete(song) print 'Pruned (deleted): ' + song.path continue if prune_modified: with open(song.path, 'rb') as f: if song.checksum != md5_for_file(f): session.delete(song) print 'Pruned (modified or no checksum): ' + song.path continue else: remaining_paths.add(song.path) else: remaining_paths.add(song.path) session.commit() return remaining_paths
def post_links(): session = Session() data = json.loads(request.data) for link in data['links']: post = Post.get_or_create(session, link['reddit_id']) subreddit = Subreddit.get_or_create(session, link['sub_name']) user = User.get_or_create(session, link['authorname']) post.subreddit_id = subreddit.id post.author_id = user.id post.domain = link['domain'] post.title = link['title'] post.url = link['url'] post.score = link['score'] post.downs = link['downs'] post.ups = link['ups'] post.is_self = link['is_self'] post.over_18 = link['over_18'] post.thumbnail = link['thumbnail'] post.created = float(link['created']) post.scraped_time = Util.now() session.add(post) session.commit() session.close() return jsonify({'received':True})
def put_batch(): session = Session() data = json.loads(request.data) worker = data['id'] users = data['users'] users = filter(lambda u: u is not None, users) usernames = [user['name'] for user in users] for lock in session.query(UserLock).join(User) \ .filter(User.name.in_(usernames), UserLock.status == UserLock.STATUS_WIP, UserLock.locker == worker): for u in users: if u['name'] == lock.user.name: if 'error' in u: eId = str(uuid4()) lock.user.reddit_id = eId else: lock.user.update_from_json(u) session.add(lock.user) session.commit() session.query(UserLock).join(User) \ .filter(User.reddit_id != None, User.name.in_(usernames), UserLock.status == UserLock.STATUS_WIP, UserLock.locker == worker) \ .update({'status': UserLock.STATUS_DONE, 'locker': None}, synchronize_session='fetch') session.commit() session.close() return jsonify({'received':'true'})
def _update_finish_times(self, user=None): """ Updates finish times for packets If a user is specified, only update given user's queue. """ session = Session() if user: packets = session.query(Packet).filter_by(user=user).order_by(Packet.arrival_time).all() else: packets = session.query(Packet).order_by(Packet.arrival_time).all() last_finish_time = {} for packet in packets: length = packet.video_length or session.query(Song).get(packet.song_id).length user = packet.user if user in last_finish_time: last_finish = max(last_finish_time[user], packet.arrival_time) packet.finish_time = last_finish + length / packet.weight() last_finish_time[user] = packet.finish_time else: packet.finish_time = packet.arrival_time + length / packet.weight() last_finish_time[user] = packet.finish_time session.commit()
def on_post(self, req, resp): doc = req.context['doc'] lat = doc['lat'] lon = doc['lon'] date_in = datetime.datetime.utcnow() if lat and lon: user = get_user(req, resp) if lon >= -79.8921061: if lon <= -79.8833942: if lat <= 36.0984408: if lat >= 36.0903956: signin = Signin(date_in=date_in, user=user) user.signedin = True Session.add(signin) Session.commit() resp.status = falcon.HTTP_201 resp.location = '/signins/%s' % (signin.id) req.context['result'] = {"action": "sign in", "result": "success"} else: resp.status = falcon.HTTP_409 req.context['result'] = {"action": "sign in", "result": "failure"} else: resp.status = falcon.HTTP_409 req.context['result'] = {"action": "sign in", "result": "failure"}
def on_get(self,req,resp,code): users=Session.query(User).all() for user in users: if str(user.code)==str(code): user.emailVerified=True resp.body="SUCCESS" Session.commit()
class TableMappingsTestCase(unittest.TestCase): def setUp(self): engine = bind_session_engine("sqlite:///:memory:", echo=False) tables.metadata.create_all(engine) self.session = Session() self.room = Room("living-room") self.item = Item("TV", self.room, "80", "plasma screen", True) self.session.add_all([self.room, self.item]) self.session.commit() def test_room_relations(self): r = self.session.query(Room).one() self.assertTrue(isinstance(r, Room)) self.assertTrue(r.name, "living-room") def test_item_relations(self): i = self.session.query(Item).one() self.assertTrue(isinstance(i, Item)) self.assertTrue(i.name, "TV") self.assertTrue(i.room, self.room) self.assertTrue(i.weight, "80") self.assertTrue(i.description, "plasma screen") self.assertTrue(i.is_fragile, True)
def _update_task_list(self, limit=10, st=0, ignore=False): session = Session() tasks = self.xunlei.get_task_list(limit, st) for task in tasks[::-1]: if len(self.task_id_sample) < TASK_ID_SAMPLE_SIZE and task['lixian_url']: self.task_id_sample.add(task['task_id']) if not self.last_task_id and task['lixian_url']: self.last_task_id = task['task_id'] db_task_status = session.query(db.Task.status).filter( db.Task.id == task['task_id']).first() if db_task_status and db_task_status[0] == "finished" and self.last_task_id: continue db_task = db.Task() db_task.id = task['task_id'] db_task.create_uid = self.uid db_task.cid = task['cid'] db_task.url = task['url'] db_task.lixian_url = task['lixian_url'] db_task.taskname = task['taskname'] db_task.task_type = task['task_type'] db_task.status = task['status'] if db_task.status == "failed": db_task.invalid = True db_task.process = task['process'] db_task.size = task['size'] db_task.format = task['format'] db_task = session.merge(db_task) if not self._update_file_list(db_task): db_task.status = "failed" db_task.invalid = True session.add(db_task) session.commit()
def load_actions(json_data): data = json.loads(json_data) items = data["items"] items.remove({}) session = Session() for item in items: action = action_from_json(item) if action and not _sgx_key_exists(session, action.sgx_key): security_query = session.query(SgxActionSecurity).filter(SgxActionSecurity.company_name == action.company_name) if (security_query.count() == 0): # New company_name security = SgxActionSecurity(company_name=action.company_name) session.add(security) else: security = security_query.one() if (security.symbol != None): action.symbol = security.symbol session.add(action) print "Added %s" % action session.commit()
def main(notify): session = Session() total = session.query(Subreddit).count() count = 0 notify("starting update of %d subs" % total) query = session.query(Subreddit).order_by("scraped_time asc") dbi = DBIterator(query=query, use_offset=None) for subreddit in dbi.results_iter(): count += 1 try: subreddit.update_from_praw(r.get_subreddit(subreddit.url.split('/')[2])) session.add(subreddit) except (praw.requests.exceptions.HTTPError, praw.errors.InvalidSubreddit) as e: print "ERROR", str(e) subreddit.touch() session.add(subreddit) if count % 2000 == 0 and notify is not None: notify("at %d of %d" % (count, total)) if count % 10 == 0: session.commit() session.commit()
def on_post(self, req, resp): doc = req.context['doc'] title = doc['title'] description = doc['description'] from_date = doc['from_date'] to_date = doc['to_date'] from_date_datetime = datetime.datetime.strptime(from_date, "%Y-%m-%d") to_date_datetime = datetime.datetime.strptime(to_date, "%Y-%m-%d") user = get_user(req, resp) event = Event(from_date=from_date_datetime, to_date=to_date_datetime, title=title, description=description, user=user) Session.add(event) Session.commit() resp.status = falcon.HTTP_201 req.context['result'] = {"action": "add event", "result": "success", "event": { 'id': event.id, 'from_date': from_date, 'to_date': to_date, 'title': event.title, 'description': event.description } }
def main(notify): session = Session() gen = session.query(User) \ .join(UserMeta) \ .filter(User.reddit_id != None, \ UserMeta.has_public_likes == UserMeta.YES, \ UserMeta.is_active != UserMeta.NO) for user in gen: try: praw_user = r.get_redditor(user.name) user.update_from_praw(praw_user) for praw_post in praw_user.get_liked(limit=100): update(session, user, praw_post, 1) for praw_post in praw_user.get_disliked(limit=100): update(session, user, praw_post, -1) user.meta.has_public_likes = UserMeta.YES except praw.requests.exceptions.HTTPError as e: print str(e) if '403' in str(e): user.meta.has_public_likes = UserMeta.NO elif '404' in str(e): user.meta.is_active = UserMeta.NO session.add(user.meta) session.add(user) session.commit() session.close()
def _update_tasks(self, tasks): session = Session() nm_list = [] bt_list = [] for task in tasks: if task.task_type in ("bt", "magnet"): bt_list.append(task.id) else: nm_list.append(task.id) for res in self.xunlei.get_task_process(nm_list, bt_list): task = self.get_task(res['task_id']) task.status = res['status'] if task.status == "failed": task.invalid = True task.process = res['process'] if res['cid'] and res['lixian_url']: task.cid = res['cid'] task.lixian_url = res['lixian_url'] task = session.merge(task) if task.status in ("downloading", "finished"): if not self._update_file_list(task): task.status = "downloading" session.add(task) session.commit()
def make_test_data(): s = Session() admin_group = Group(name='admin') users_group = Group(name='users') admin = User( username='******', password='******', email='*****@*****.**', firstname='Tim', lastname='Radke') admin.groups.extend([admin_group, users_group]) s.add(admin) groups = [] for i in xrange(1,6): fg = ForumGroup(name='Forum Group %s' % i, position=i) s.add(fg) groups.append(fg) first_group = groups[0] for i in xrange(1, 6): f = Forum(name='Test Forum %s' % i, position=i) f.forum_group = first_group s.add(f) s.commit()
def event(event_id): content = {'events': 'test'} success = {'status': 'event created'} updateSuccess = {'status':'account updated'} noEvent = {'error': 'User not found.'} updateError = {'error': 'User not found/input validation failed.'} error = {'error': "Error in JSON/SQL syntax"} if request.method == 'POST': data = request.json if event.createEvent(data): return success, status.HTTP_200_OK else: return error, status.HTTP_500_INTERNAL_SERVER_ERROR if request.method == 'GET': s = Session() e = s.query(Event).filter_by(id=event_id).first() if e: return Event.asdict(e), status.HTTP_200_OK else: return noEvent, status.HTTP_404_NOT_FOUND if request.method == 'POST': data = request.json if data: s = Session() u = s.query(Event).filter_by(id=event_id).update(data) if u: s.commit() s.close() return updateSuccess, status.HTTP_200_OK else: return updateError, status.HTTP_400_BAD_REQUEST
class MemberTracker(object): def __init__(self, repository_name, new_members=True, odd_hours=False): self.session = Session(); self.repository_name = repository_name; self.new_members = new_members; @classmethod def doc_name(cls, member_identifier): return "%s" % (member_identifier,) @classmethod def tool_name(cls): return "Detection::Behavior::Members" def check_if_new(self, member_identifier, add_if_new=True, alert_function=None): if member_identifier is None: return False name = MemberTracker.doc_name(member_identifier) tool = MemberTracker.tool_name() repo, did_add = get_one_or_create(self.session, Repo, name=self.repository_name) members_doc, did_add = get_one_or_create(self.session, RepoDocument, repo=repo, tool=tool, name=name) if did_add: members_doc.data = {} if alert_function: alert_function(member_identifier) self.session.commit() return True self.session.commit() return False
def addPost(): title = request.form.get('title') year = request.form.get('year') session = Session() m = Movie(title=title, year=year) session.add(m) session.commit() return redirect('/')
def delete_file(id): session = Session() session.query(File).filter(File.id==id).delete() session.commit() return redirect(url_for('manage_files'))
def get_album(album): songs = [] if album: session = Session() res = session.query(Song).filter_by(album=album).order_by(Song.tracknumber, Song.path).all() session.commit() songs = [song.dictify() for song in res] return {'query': album, 'results': songs}
def play(): session = Session() entites = session.query(Entity).filter(Entity.type == 'song').all() session.commit() return render_template("playlist.html", entities=entites)
def remove_beer(beer_name): session = Session() beer = session.query(Beer).filter_by(name=beer_name.lower()).one() session.delete(beer) session.commit() response = jsonify() response.status_code = 201 return response
def log(user, message): if not LOGGING_ENABLED: return session = Session() message = AuditLogMessage( user=user, message=message, player_name=PLAYER_NAME) session.add(message) session.commit()
def delete_series_job(id): session = Session() session.query(SeriesJob).filter(SeriesJob.id==id).delete() session.commit() return redirect(url_for('index'))
def delete_note(id): session = Session() session.query(Note).filter(Note.id==id).delete() session.commit() return redirect(url_for('index'))
def updata_recruit(): """ 修复数据库中的结果 :return: """ session = Session() list_recruit = session.query(Recruit).all() for rec in list_recruit: rec.salary = rec.salary.upper() session.commit()
def getOrInitializeUser(userid): user = session.query(User).filter(User.slack_id == userid).one_or_none() if user is None: profile_info = slack_client.api_call("users.info", user=userid) if profile_info['ok']: user = User(name=profile_info['user']['profile']['first_name'], skill="nope") else: user = User(name="unknown", skill="nope") session.add(user) session.commit() return user
def update_current_week(): page = unecon_request(group_id=12837) page_parser = UneconParser(page.content) current_week = page_parser.get_current_week_number() session = Session() current_week_obj = CurrentWeek(week=current_week, date=datetime.datetime.now()) session.add(current_week_obj) session.commit() session.close()
def delete(name): session = Session() effected_rows = session.query(PlaceDAO).filter( PlaceDAO.name == name).delete() session.commit() session.close() if effected_rows == 0: return jsonify( {'message': f'There is no place record with id {name}'}), 404 else: return jsonify({'message': 'The place record was removed'}), 200
def search_songs(query, limit=20): songs = [] if query: session = Session() res = session.query(Song).filter( or_(Song.title.like('%' + query + '%'), Song.artist.like('%' + query + '%'), Song.album.like('%' + query + '%'))).limit(limit).all() session.commit() songs = [song.dictify() for song in res] return {'query': query, 'limit': limit, 'results': songs}
def post(self): session = Session() new_user = db.User(flask.request.form['username'], flask.request.form['first_name'], flask.request.form['last_name'], flask.request.form['password']) session.add(new_user) session.commit() flask.flash('Welcome! Please log in now!') return flask.redirect(flask.url_for('login'))
def create_account(body): session = Session() account = AccountDAO(body['customer_name'], body['customer_address'], body['customer_email'], body['customer_password'], datetime.now()) #Simply add objects to table, advantage of ORM session.add(account) session.commit() session.refresh(account) session.close() #Use Jsonify to return json object with status code when API is called. return jsonify({'customer_id': account.id}), 200
def create_or_update_user(telegram_id): session = Session() user = session.query(User).filter_by(telegram_id=telegram_id).first() if not user: user = User(telegram_id=telegram_id) session.add(user) session.commit() session.close() return user
def func(self, character, args, text): z = Zone(builder_id=character.id, name='New Zone #') s.add(z) s.commit() z.name = f'{z.name}{z.id}' character.notify(f'Created zone {z.name}.') r = Room(zone_id=z.id, name='The First Room') s.add(r) s.commit() character.notify(f'Created room {r}.') character.move(r) character.show_location()
def register_product(body): session = Session() product = ProductDAO(body['title'], body['overview'], body['release_date'], body['runtime'], body['adult'], body['original_language'], body['budget'], body['revenue'], body['product_quantity'], body['unit_price']) session.add(product) session.commit() session.refresh(product) session.close() return jsonify({'product_id': product.id}), 200
def insert(user_id,login_type,time,msg,u_uuid,remark=''): session_obj = Session() tmp = session_obj.query(user_info).filter_by(id=user_id).first() if(tmp ==None): Session.remove() return -1 package_obj = logger(user_id = user_id,login_type= login_type,time =time,msg=msg,u_uuid=u_uuid,remarks = remark ) session_obj.add(package_obj) session_obj.commit() Session.remove() return 0
def delete(p_id): session = Session() delete_row = session.query(ProductDAO).filter( ProductDAO.id == p_id).delete() session.commit() session.close() if delete_row == 0: return jsonify( {'message': f'There is no product to delete with id {p_id}'}), 404 else: return jsonify({'message': 'The product is removed from db'}), 200
def Person_education_update(_id): """ Редагування даних в рядку таблиці про освіту за id запису. В групу Education :param _id: id запису в таблиці про освіту """ session = Session() data = request.json session = Session() session.query(Education).filter(Education.id == _id).update(data) session.commit() session.close() return 'ok'
def create(body): session = Session() delivery = DeliveryDAO( body['customer_id'], body['provider_id'], body['package_id'], datetime.now(), datetime.strptime(body['delivery_time'], '%Y-%m-%d %H:%M:%S.%f'), StatusDAO(STATUS_CREATED, datetime.now())) session.add(delivery) session.commit() session.refresh(delivery) session.close() return jsonify({'delivery_id': delivery.id}), 200
def post(self): session = Session() request_data = json.loads(request.data.decode('utf-8')) if is_product_data_valid(request_data): product = self.model.from_dict(request_data) session.add(product) session.commit() return jsonify('ok') else: response = jsonify('data error') response.status_code = 400 return response
def showAnswers(q_id): list = [] sess = Session() for instance in sess.query(Answer).filter_by(questionID=q_id): if instance.isPublished: ans = [ instance.id, instance.answerer, instance.content, instance.numAgree, instance.numCollect, instance.date ] list.append(ans) sess.commit() return list
def get_history(limit=20): session = Session() history_items = (session.query(PlayHistory) .filter_by(player_name=PLAYER_NAME) .order_by(PlayHistory.id.desc()).limit(limit).all()) session.commit() songs = [] for item in history_items: song_obj = session.query(Song).get(item.song_id).dictify() song_obj['played_at'] = str(item.played_at) songs.append(song_obj) return {'limit': limit, 'results': songs}
def _update_task_list(self, limit=10, st=0, ignore=False): now = self.time() with self._last_update_task_lock: if now <= self._last_update_task and limit <= self._last_update_task_size: return self._last_update_task = self.time() self._last_update_task_size = limit session = Session() tasks = self.xunlei.get_task_list(limit, st) for task in tasks[::-1]: db_task_status = session.query(db.Task.status).filter( db.Task.id == task['task_id']).first() if db_task_status and db_task_status[0] == "finished": continue db_task = self.get_task(int(task['task_id'])) changed = False if not db_task: changed = True db_task = db.Task() db_task.id = task['task_id'] db_task.create_uid = self.uid db_task.cid = task['cid'] db_task.url = task['url'] db_task.lixian_url = task['lixian_url'] db_task.taskname = task['taskname'] or "NULL" db_task.task_type = task['task_type'] db_task.status = task['status'] db_task.invalid = True db_task.process = task['process'] db_task.size = task['size'] db_task.format = task['format'] else: db_task.lixian_url = task['lixian_url'] if db_task.status != task['status']: changed = True db_task.status = task['status'] if db_task.status == "failed": db_task.invalid = True if db_task.process != task['process']: changed = True db_task.process = task['process'] session.add(db_task) if changed and not self._update_file_list(db_task, session): db_task.status = "failed" db_task.invalid = True session.add(db_task) session.commit() session.close()
def leaderboard_all(message): session = Session() chat = session.query(Chats).filter( Chats.chat_id == message.chat.id).first() if chat == None: return leaderboard = session.query(Leaderboard).order_by(Leaderboard.place).all() msg_text = tabulate([[leader.place, leader.captain_name, leader.score] for leader in leaderboard], headers=['', 'PLAYER', 'SCORE']) session.commit() session.close() bot.reply_to(message, "`" + msg_text + "`", parse_mode="Markdown")
def add(cls,search_query,user_id): session = Session() srch_query= session.query(cls).filter(*[cls.search_query==search_query,cls.user_id==str(user_id)]).all() print(srch_query) if len(srch_query)!=0: srch_query[0].searched_at=datetime.datetime.utcnow() session.commit() session.close() else: srch_query=cls(user_id=str(user_id),search_query=search_query) session.add(srch_query) session.commit() session.close()
def api_admin_branch_status(_id, status): """ зміна статусу філіалу """ session = Session() resp = session.query(func.count(Worker.id)).filter( Worker.status == 'active').filter(Worker.fk_branch == _id).first() if resp[0] > 0 and status == 'not active': return jsonify( 'Неможливо деактивувати філіал оскільки в ньому є працівники') session.query(Branch).filter(Branch.id == _id).update({'status': status}) session.commit() return jsonify('ok')
def create_or_get_tag(title): session = Session() tag = session.query(Tag).filter_by(title=title).first() if not tag: tag = Tag(title=title) session.add(tag) session.commit() tag_id = tag.id session.close() return tag_id
def create_or_get_user(username): session = Session() user = session.query(User).filter_by(username=username).first() if not user: user = User(username=username) session.add(user) session.commit() user_id = user.id session.close() return user_id
def insertAnswer(answerer, questionID, content, isPublished): sess = Session() date = time.strftime("%Y_%m_%d", time.localtime()) new_answer = Answer(answerer=answerer, questionID=questionID, content=content, isPublished=isPublished, numAgree=0, numCollect=0, date=date) sess.add(new_answer) sess.commit() return new_answer.id
def api_updatenotes(): """ Редагування нотатки. В групу Note """ session = Session() data = request.json session.query(Note).filter_by(id=data['id']).update({ "name": data['name'], "text": data['text'] }) session.commit() session.close() return jsonify('ok')
def insert_members(): session = Session() mdf = pd.read_csv('data/application_team_data.csv') try: for i in mdf.index: member = Member(int(mdf['ID'][i]), mdf['Name'][i]) session.add(member) session.commit() except Exception as e: print(e) session.rollback() finally: session.close()
def api_admin_branch_update(_id): """ Редагування філіалу. :param _id: ід філіалу """ session = Session() data = request.json print(data) session.query(Branch).filter(Branch.id == _id).update(data) session.commit() session.close() return 'ok'
def create_or_get_post(user_id, title, text): session = Session() post = session.query(Post).filter_by(title=title).first() if not post: post = Post(title=title, text=text, user_id=user_id) session.add(post) session.commit() post_id = post.id session.close() return post_id
def setUp(self): Base.metadata.drop_all(engine) Base.metadata.create_all(engine) row1 = Signature(X=1, Y=2, Z=3) row2 = Signature(X=4, Y=5, Z=6) row3 = Signature2(A=1, B=2, C=3) row4 = Signature2(A=4, B=5, C=6) session = Session() session.add(row1) session.add(row2) session.add(row3) session.add(row4) session.commit()
def api_admin_city(): """ Додавання нового міста. """ session = Session() data = request.json city_in_db = session.query(City).filter(City.name == data['name']).first() if not city_in_db: new_city = City(**data) session.add(new_city) session.commit() session.close() return 'ok'