def upload(request): if request.content_length/1000000 > 20: return error_response(400, 'Sorry, but the file must be under 20MB.') # Create photo object in database photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length) DBSession.add(photo) DBSession.flush() # Save uploaded file input_file = request.POST['file'].file input_file.seek(0) if not os.path.exists('data'): os.makedirs('data') if not os.path.exists('data/uploads'): os.makedirs('data/uploads') upload_path = os.path.join('data', 'uploads', str(photo.id)) with open(upload_path, 'w') as f: shutil.copyfileobj(input_file, f) # Check the content type and rename as appropriate mime = magic.from_file(upload_path, mime=True) if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']: resp = Response('Sorry, but we can only accept jpg, gif, or png files.') resp.status_code = 400 resp.status_string = '400 Bad Request' return resp extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg', 'image/gif': '.gif', 'image/png': '.png', 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime] os.rename(upload_path, upload_path + extension) photo.content_type = mime return Response('OK')
def eventAdd(request): eventName = request.POST['name'] eventType = request.POST['type'] eventDescription = request.POST['description'] image = request.POST.getall('file') for i in image: imageId = uuid.uuid1() imageUrl = str(imageId) open('/home/mohit/intern/hallwala/HallWala/hallwala/images/%d.jpg' % (imageId), 'wb').write(i.file.read()) for infile in glob.glob("/home/mohit/intern/hallwala/HallWala/hallwala/images/*.jpg"): im = Image.open(infile) # don't save if thumbnail already exists if infile[0:2] != "T_": # convert to thumbnail image im.thumbnail((128, 128), Image.ANTIALIAS) # prefix thumbnail file with T_ im.save("T_" + infile, "JPEG") newEvent = Event(eventName,eventType,eventDescription) DBSession.add(newEvent) DBSession.flush() event = newEvent.getJSON() return {'event' : event}
def post_entry(request): entry = m.Entry() entry.start_datetime = datetime.datetime.now() entry.updated_datetime = datetime.datetime.now() DBSession.add(entry) DBSession.flush() return entry.entry_id
def attach_pictures(request): menu_query = DBSession.query(Menu).filter(Menu.id==request.matchdict['menu_id']) images_id = menu_query.one().images_id images_id = images_id.split(' ') if images_id else [] if images_id: images = DBSession.query(Image).filter(Image.id.in_(images_id)).all() added_thumbs = [] if "data" in request.params: data = json.loads(request.params["data"]) for image_info in data: image, thumb = image_info if not image or not thumb: continue ext = os.path.splitext(image)[-1].lower() if ext in (".jpg", ".jpeg", ".png"): new_image = Image(image_url=image, thumb_url=thumb) added_thumbs.append(thumb) DBSession.add(new_image) DBSession.flush() DBSession.refresh(new_image) images_id.append(new_image.id) menu_query.update({ "images_id": ' '.join([str(i) for i in images_id]), }) return json.dumps(added_thumbs)
def postAdd(request): currentUser = int(authenticated_userid(request)) rankWeight = None #TODO pasteTitle = request.POST['paste_title'] topic_id = request.POST['topic'] newPost = Post(currentUser,rankWeight,topic_id,pasteTitle) DBSession.add(newPost) DBSession.flush() contentTitles = [] contentURLs = [] for key, value in request.POST.iteritems(): if key == "title" and value != "": contentTitles.append(value) elif key == "URL" and value != "": contentURLs.append(value) contents = [] for title,URL in zip(contentTitles,contentURLs): contentType = "LINK" # TODO newContent = Content(title,URL,contentType,newPost.id) DBSession.add(newContent) DBSession.flush() contents.append(row2dict(newContent)) post = {} post['post'] = row2dict(newPost) post['contents'] = contents return {'post' : post}
def create_translation(client_id, contents=list(), gist_type='Service'): gist = TranslationGist(client_id=client_id, type=gist_type) DBSession.add(gist) DBSession.flush() for content in contents: atom = TranslationAtom(client_id=client_id, content=content[0], locale_id=content[1], parent=gist) DBSession.add(atom) DBSession.flush() return gist
def add_money(player_in, amount): in_player = Player.query.filter(Player.id == int(player_in)).first() movement_in = Movement(player=in_player, amount=amount, move_type=Movement.TYPES['IN']) DBSession.add(movement_in) in_player.update_balance(operation_type=Movement.TYPES['IN'], amount=amount) DBSession.flush() DBSession.commit()
def create_user(username, password): logging.debug("creating user %s" % (username)) if find_user(username): raise RuntimeError("User %s already exists" % (username)) hashed_password = hash_password(password) u = User(username=username, password=hashed_password) DBSession.add(u) DBSession.flush() DBSession.expunge(u) return u
def make_session(user, sessionid=None, expires_in=3600): if not sessionid: sessionid = str(uuid.uuid4()) DBSession.query(Session).filter(Session.sessionid == sessionid).delete() logging.debug("making session for %s with sessionid %s" % (user.username, sessionid)) s = Session(user_id=user.id, sessionid=sessionid, expires=datetime.datetime.now() + datetime.timedelta(0, expires_in)) DBSession.add(s) DBSession.flush() DBSession.expunge(s) return s
def subtract_money(player_out, amount): out_player = Player.query.filter(Player.id == int(player_out)).first() movement_out = Movement(player=out_player, amount=amount, move_type=Movement.TYPES['OUT']) DBSession.add(movement_out) out_player.update_balance(operation_type=Movement.TYPES['OUT'], amount=amount) DBSession.flush() DBSession.commit()
def add_players_command(num_of_players): '''num_of_players: Numero de jogadores''' for p in range(int(num_of_players)): player_name = 'Jogador {}'.format(p + 1) player = Player(player_name=player_name) DBSession.add(player) player = Player(player_name='Banqueiro', balance=float(1000000.00)) DBSession.add(player) DBSession.flush() DBSession.commit()
def add_record(self): """Verifies post form and saves record to database.""" form_json = self.request.json with transaction.manager: record = Record.from_dict(form_json) DBSession.add(record) # refresh record before commit to send creted Record in response DBSession.flush() DBSession.refresh(record) response_json = record.to_json() transaction.commit() return Response(status=201, json=response_json)
def post_spending_item(request): spending = m.Spending() print(request.body) spending.amount = request.get_json('amount') spending.category_id = request.get_json('categoryId') spending.incurred_begin_date = request.get_json('incurredBeginDate') spending.incurred_end_date = request.get_json('incurredEndDate') spending.note = request.get_json('note') spending.paid_date = request.get_json('paidDate') spending.recipient = request.get_json('recipient') DBSession.add(spending) DBSession.flush() return spending.spending_id
def add_servers(self): data = self.request.json with transaction.manager: server = Server(**data) DBSession.add(server) DBSession.flush() qs = DBSession.query(Server) qs.session.refresh(server) return { 'uid': server.uid, 'address': server.address, 'port': server.port, 'useSSL': server.useSSL }
def userSignup(request): name = request.POST['name'] email = request.POST['email'] password = hashlib.sha256(request.POST['password']).hexdigest() dbFoundUser = DBSession.query(User.id).filter(User.email == email).first() if dbFoundUser: return dict(status = 0) userToSave = User(name,email,password) DBSession.add(userToSave) DBSession.flush() headers = remember(request,userToSave.id) return HTTPFound(location = request.route_url('home'), headers = headers)
def topicFollow(request): currentUser = int(authenticated_userid(request)) topicId = int(request.matchdict['topic_id']) followed = DBSession.query(UserFollowedTopic).\ filter(and_(UserFollowedTopic.topic_id == topicId,UserFollowedTopic.user_id == currentUser)).\ first() if followed != None: return {'status' : 'Already Following'} newTopicFollow = UserFollowedTopic(topicId,currentUser) DBSession.add(newTopicFollow) DBSession.flush() return {'status' : 'Follwed'}
def start_game_command(num_of_players): '''num_of_players: Numero de jogadores''' click.secho("Iniciando novo jogo com {} jogadores\n".format(num_of_players), fg='yellow', bold=True) initialisedb() with click.progressbar(range(int(num_of_players))) as players: for p in players: player_name = 'Jogador {}'.format(p + 1) click.secho(' Inserindo jogador {0}'.format(player_name), fg='blue') player = Player(player_name=player_name) DBSession.add(player) player = Player(player_name='Banqueiro', balance=float(1000000.0)) DBSession.add(player) DBSession.flush() DBSession.commit() click.secho('[OK]', fg='green', bold=True)
def topicUnfollow(request): currentUser = int(authenticated_userid(request)) topicId = int(request.matchdict['topic_id']) followed = DBSession.query(UserFollowedTopic).\ filter(and_(UserFollowedTopic.topic_id == topicId,UserFollowedTopic.user_id == currentUser)).\ first() if followed == None: return {'status' : 'Not Following'} DBSession.delete(followed) DBSession.flush() DBSession.commit() return {'status' : 'Unfollowed'}
def postLike(request): currentUser = int(authenticated_userid(request)) postId = int(request.matchdict['post_id']) liked = DBSession.query(PostLike).\ filter(and_(PostLike.post_id == postId,PostLike.user_id == currentUser)).\ first() if liked != None: return {'status' : 'Already UpVoted'} newPostLike = PostLike(postId,currentUser) DBSession.add(newPostLike) DBSession.flush() return {'status' : 'UpVoted'}
def create_person(self): '''does some silly random person creation''' import random import models firstnames = [ 'Donald', 'Gustav', 'Dagobert', 'Walter', 'Brian', 'Holger'] lastnames = [ 'Duck', 'Smith', 'Gstierbreitner', 'Welanhans', 'Buschenschank'] pers = models.Person( firstname=random.choice(firstnames), lastname=random.choice(lastnames)) pers.addresses.append( models.Address(city='Entenhausen', street='Erpelweg 13')) DBSession.add(pers) DBSession.flush() transaction.commit() return Response('Added %s %s' % (pers.firstname, pers.lastname))
def postTagAdd(request): currentUser = int(authenticated_userid(request)) postId = int(request.matchdict['post_id']) tagName = request.POST['tag_name'] dbPostTag = DBSession.query(PostTag).\ filter(and_(PostTag.post_id == postId,PostTag.tag_name == tagName)).\ first() if dbPostTag != None: return {'status' : 'Tag Already Present'} newPostTag = PostTag(postId,tagName) DBSession.add(newPostTag) DBSession.flush() return {'status' : 'Tag Added'}
def save_word_data(self, most_common): """ Saves the 100 most common word data into the database. """ objs = [] for word, num in most_common: w_obj = DBSession.query(WordUsage).filter(WordUsage.word == word) if w_obj.count() > 0: w_obj = w_obj.first() w_obj.count += num DBSession.merge(w_obj) else: w_obj = WordUsage(word=word, count=num) objs.append(w_obj) if len(objs) > 0: DBSession.bulk_save_objects(objs) DBSession.flush() DBSession.commit() raise gen.Return(False)
def create_menu_item(request): #create the new menu item entry new_menu_item = MenuItem(name=request.params['name'].encode('utf8'), description=request.params['description'].encode('utf8'), menu_id=request.matchdict['menu_id'], healthy=int(request.params['healthy'])) DBSession.add(new_menu_item) DBSession.flush() DBSession.refresh(new_menu_item) #create corresponding allergens for allergen in ALLERGENS: if allergen in request.params: new_allergen = Allergen(menu_item_id=new_menu_item.id, allergen = allergen) DBSession.add(new_allergen) #find the corresponding menu menuQuery = DBSession.query(Menu).filter(Menu.id==request.matchdict['menu_id']) menu = menuQuery.one() menu_items = menu.menus #update the menu items on the menu if len(menu_items) > 0: #just append menu_items = menu_items.split(' ') menu_items = map(int, menu_items) menu_items.append(int(new_menu_item.id)) else: #create the first one menu_items = [int(new_menu_item.id)] menu_items_string = ' '.join(str(menu_item_id) for menu_item_id in menu_items) menu.menus = menu_items_string menuQuery.update({"menus":menu_items_string}, synchronize_session=False) #update menu name if needed first_menu_item = DBSession.query(MenuItem).filter(MenuItem.id==menu_items[0]).one() #if we just inserted the first item in the menu, update the menu name with the first item name if first_menu_item.id == new_menu_item.id: menuQuery.update({"name":first_menu_item.name}) #update google calendar update_gcalendar(menu) url = request.route_url('edit_menu', cafe_id=int(request.matchdict['cafe_id']), menu_id=request.matchdict['menu_id']) return HTTPFound(location=url)
def addComment(request): if Redirect(request): return HTTPFound(location = "http://felicity.iiit.ac.in/threads/cachein/") if request.POST: comment = request.POST['comment'] if comment == None or comment == "": return dict(status = 0) currentUser = int(authenticated_userid(request)) user = DBSession.query(User).filter(User.id == currentUser).first() currentQuestion = user.question.id commentToSave = Comment(comment,currentQuestion,currentUser) DBSession.add(commentToSave) DBSession.flush() return dict(status = 1) else: return dict(status = 0)
def bootstrap_database(): # # Create default admin user # password = "" dbsession = DBSession() if options.setup.lower().startswith('dev'): admin_user = '******' password = '******' else: admin_user = unicode(raw_input(PROMPT + "Admin username: "******"New Admin ") sys.stdout.flush() password1 = getpass.getpass() sys.stdout.write(PROMPT + "Confirm New Admin ") sys.stdout.flush() password2 = getpass.getpass() if password1 == password2 and 12 <= len(password1): password = password1 else: print(WARN + 'Error: Passwords did not match, or were less than 12 chars') sys.exit() user = User(name=admin_user, password=password) dbsession.add(user) dbsession.flush() admin_permission = Permission(name=ADMIN_PERMISSION, user_id=user.id) user.permissions.append(admin_permission) dbsession.add(admin_permission) dbsession.add(user) # # Commit it all # dbsession.commit()
def addQuestion(request): if Redirect(request): return HTTPFound(location = "http://felicity.iiit.ac.in/threads/cachein/") if request.POST: question = request.POST['question'] questionToSave = Question(question) DBSession.add(questionToSave) DBSession.flush() next_qid = [] points = [] error = False for key, value in request.POST.iteritems(): if key == "next_qid" and value != "": next_qid.append(value) elif key == "points" and value != "": points.append(value) k = 0 for key, value in request.POST.iteritems(): if key == "answer" and value != "": if next_qid[k] == "" or points[k] == "": error = True else: answerToSave = Answer(qid = questionToSave.id, next_qid = next_qid[k], answer = value, points = points[k]) DBSession.add(answerToSave) DBSession.flush() k = k + 1 elif key == "attachment" and value != "": filename = value.filename input_file = value.file file_path = os.path.join('cachein/static/attachments', '%s' % filename) temp_file_path = file_path + '~' output_file = open(temp_file_path, 'wb') input_file.seek(0) while True: data = input_file.read(2<<16) if not data: break output_file.write(data) output_file.close() os.rename(temp_file_path, file_path) attachmentToSave = Attachment(qid = questionToSave.id, type = filename.split(".")[-1], attachment = filename) DBSession.add(attachmentToSave) DBSession.flush() return dict(status = "done") return dict(status = "")
def create_menu(request): #see if there's already a menu created with the same params m = request.matchdict menu = DBSession.query(Menu).filter(Menu.cafe_id==request.matchdict['cafe_id']) if 'date' in request.params: menu = menu.filter(Menu.date==request.params['date']) if 'time' in request.params: menu = menu.filter(Menu.time_sort_key==int(request.params['time'])) menu = menu.first() #if not, create one if menu is None: # verify date date = request.params['date'] if date is '0000-00-00': return HTTPFound(location= request.route_url('edit_menus_today')) menu = Menu(cafe_id=int(m['cafe_id']), name='', date=request.params['date'], time_sort_key=request.params['time'], menus='', sent=False) DBSession.add(menu) DBSession.flush() DBSession.refresh(menu) url = request.route_url('edit_menu', cafe_id=int(m['cafe_id']), menu_id=menu.id, allergen_list=ALLERGENS, healthy_factor=HEALTHY_FACTOR) update_gcalendar(menu) return HTTPFound(location=url)
def checkSolution(request): if Redirect(request): return HTTPFound(location = "http://felicity.iiit.ac.in/threads/cachein/") currentUser = int(authenticated_userid(request)) user = DBSession.query(User).filter(User.id == currentUser).first() currentQuestion = user.question.id userAnswer = request.POST['answer'] userAnswer = __neatifyAnswer(userAnswer) possibleAnswers = DBSession.query(Answer).filter(Answer.qid == currentQuestion).all() for answer in possibleAnswers: if answer.answer == userAnswer: user.cur_question = answer.next_qid user.score += answer.points user.last_submit_time = getTimeEpoch() DBSession.flush() return dict(status = 1) return dict(status = 0)
def populate(comps='comps-f16', do_dependencies=True): from yum.comps import Comps session = DBSession() c = Comps() c.add('comps/%s.xml' % comps) for group in c.groups: g = Group(id=group.groupid, name=group.name, description=group.description) session.add(g) for package in group.packages: p = session.query(Package).filter_by( name=to_unicode(package)).first() if not p: p = Package(name=package) session.add(p) p.group = g session.flush() root = Root(name=u'Fedora') session.add(root) session.flush() for category in c.categories: c = Category(id=category.categoryid, name=category.name, description=category.description) session.add(c) root.categories.append(c) for group in category.groups: g = session.query(Group).filter_by( group_id=to_unicode(group)).first() if not g: print "Cannot find group: %s" % group else: g.category = c session.flush() if do_dependencies: for package in session.query(Package).all(): add_dependencies(package, session) session.commit()
def populate(comps='comps-f16', do_dependencies=True): from yum.comps import Comps session = DBSession() c = Comps() c.add('comps/%s.xml' % comps) for group in c.groups: g = Group(id=group.groupid, name=group.name, description=group.description) session.add(g) for package in group.packages: p = session.query(Package).filter_by(name=to_unicode(package)).first() if not p: p = Package(name=package) session.add(p) p.group = g session.flush() root = Root(name=u'Fedora') session.add(root) session.flush() for category in c.categories: c = Category(id=category.categoryid, name=category.name, description=category.description) session.add(c) root.categories.append(c) for group in category.groups: g = session.query(Group).filter_by(group_id=to_unicode(group)).first() if not g: print "Cannot find group: %s" % group else: g.category = c session.flush() if do_dependencies: for package in session.query(Package).all(): add_dependencies(package, session) session.commit()
dice = DiceTemplate(name, dice_info['Description'], dice_type, race, role, autosave=autosave) DBSession.add(dice) #Add color if (dice_info['Element_ID_1'] != 'NONE'): color1 = DiceElement(dice, conversion_color[dice_info['Element_ID_1']]) DBSession.add(color1) if (dice_info['Element_ID_2'] != 'NONE'): color2 = DiceElement(dice, conversion_color[dice_info['Element_ID_2']]) DBSession.add(color2) cursor.execute("SELECT * from Dice_Sides as a LEFT JOIN Dice_Faces as b ON a.Face_ID = b.Face_ID WHERE a.Die_ID = '"+dice_info['Die_ID']+"'") face_result = cursor.fetchall() faces = [] for face_info in face_result: if face_info['Icon_ID'] == 'ID' and name == 'Wolf Pack': face = 'GroupID' else: face = conversion_icon[face_info['Icon_ID']] if face_info['Icon_ID'] == 'GALEFORCE' or face_info['Icon_ID'] == 'ILLUSION': amount = 1 else: amount = face_info['Quantity'] face = DiceFaceTemplate(dice, face_info['SideNumber'], conversion_icon[face_info['Icon_ID']], amount, face_info['Image']) faces.append(face) DBSession.add(face) DBSession.flush()
def create_object(object_class, **object_data): obj = object_class(**object_data) DBSession.add(obj) DBSession.flush() return obj
sys.stdout.write(PROMPT+"New Admin ") sys.stdout.flush() password1 = getpass.getpass() sys.stdout.write(PROMPT+"Confirm New Admin ") sys.stdout.flush() password2 = getpass.getpass() if password1 == password2 and 12 <= len(password1): password = password1 else: print(WARN+'Error: Passwords did not match, or were less than 12 chars') os._exit(1) dbsession = DBSession() user = User(name=admin_user, password=password) dbsession.add(user) dbsession.flush() admin_permission = Permission(name=ADMIN_PERMISSION, user_id=user.id) user.permissions.append(admin_permission) dbsession.add(admin_permission) dbsession.add(user) dbsession.commit() # Display Details if config.bootstrap == 'developement': environ = bold + R + "Developement boot strap" + W details = ", default admin password is '%s'." % password else: environ = bold + "Production boot strap" + W details = '.' print INFO + '%s completed successfully%s' % (environ, details)
old_UserBlobs, BaseGroup as old_BaseGroup, Group as old_Group, Language as old_Language, Dictionary as old_Dictionary, DictionaryPerspective as old_DictionaryPerspective, DictionaryPerspectiveField as old_Field, UserEntitiesTranslationString, UITranslationString, Email as old_Email, Passhash as old_Passhash, LexicalEntry as old_LexicalEntry, LevelOneEntity as old_l1entity, LevelTwoEntity as old_l2entity, GroupingEntity as old_grentity, PublishLevelOneEntity as old_publ1entity, PublishLevelTwoEntity as old_publ2entity, PublishGroupingEntity as old_pubgrentity) import json for locale in old_DBSession.query(old_Locale).all(): new_locale = Locale(id=locale.id, shortcut=locale.shortcut, intl_name=locale.intl_name) DBSession.add(new_locale) DBSession.flush() for user in old_DBSession.query(old_User).all(): new_user = User(id=user.id, login=user.login, name=user.name, intl_name=user.intl_name, birthday=user.birthday, created_at=user.signup_date, is_active=user.is_active) if user.default_locale_id: new_user.default_locale_id = user.default_locale_id DBSession.add(new_user) DBSession.flush() for client in old_DBSession.query(old_Client).all(): new_client = Client(id=client.id, user_id=client.user_id,