def get(self): self.response.content_type = 'text/json' if self.request.get('after'): latest_meme_key = ndb.Key(urlsafe=self.request.get('after')) latest_meme = latest_meme_key.get() new_meme_query = Meme.query(Meme.created_at > latest_meme.created_at).order(-Meme.created_at) else: new_meme_query = Meme.query().order(-Meme.created_at) user_id = self.request.get('after') if user_id: new_meme_query = new_meme_query.filter(Meme.creator == user_id) new_memes = new_meme_query.fetch() new_memes_list = [] for meme in new_memes: image = meme.image.get() new_memes_list.append({ 'image_file': image.image_file, 'top_text': meme.top_text, 'middle_text': meme.middle_text, 'bottom_text': meme.bottom_text, 'created_at': meme.created_at.isoformat(), 'key': meme.key.urlsafe(), }) self.response.write(json.dumps(new_memes_list))
def post(self): meme = Meme(line1=self.request.get('user-first-ln'), line2=self.request.get('user-second-ln'), img_choice=self.request.get('meme-type')) meme_key = meme.put() self.response.write("Meme created: " + str(meme_key) + "<br>") self.response.write("<a href='/allmemes'>All memes</a>")
def post(self): ''' Endpoint for registering a meme ''' parser = reqparse.RequestParser() parser.add_argument('url', required=True) parser.add_argument('title') args = parser.parse_args() if Meme.query.filter_by(url=args.url).first(): return send_error("This meme has already been submitted! " "Lay off the stale memes.", 400) try: args.url = validate_imgur_link(args.url) except ValueError as e: logger.info('%s sent an invalid imgur link.' % flask.g.netid) return send_error(str(e)) meme = Meme( url=args.url, title=args.title, netid=flask.g.netid ) db.session.add(meme) db.session.commit() logger.info("%s created new meme with id %s" % (flask.g.netid, meme.id)) return jsonify(meme.to_dict())
def post(self): checkLoggedInAndRegistered(self) user = users.get_current_user() meme = Meme(line1=self.request.get('user-first-ln'), line2=self.request.get('user-second-ln'), owner=user.nickname(), img_choice=self.request.get('meme-type')) meme_key = meme.put() self.response.write("Meme created: " + str(meme_key) + "<br>") self.response.write("<a href='/allmemes'>All memes</a> | ") self.response.write("<a href='/usermemes'>My memes</a>")
def post(self): top_line = self.request.get("top-line") bottom_line = self.request.get("bottom-line") meme_url = self.request.get("template") newMeme = Meme(url = meme_url, top_text = top_line,bottom_text = bottom_line) newMeme.put() results = { "top" : top_line, "bottom" : bottom_line, "url" : meme_url } result_template = jinja_env.get_template('result.html') self.response.write(result_template.render(results)) print(top_line)
def post(self): results_template = the_jinja_env.get_template('templates/results.html') meme_first_line = self.request.get('user-first-ln') meme_second_line = self.request.get('user-second-ln') meme_img_choice = self.request.get('meme-type') user_meme = Meme(first_line = meme_first_line, second_line = meme_second_line, pic_type = meme_img_choice) user_meme.put() the_variable_dict = {"line1": meme_first_line, "line2": meme_second_line, "img_url": user_meme.get_meme_url()} self.response.write(results_template.render(the_variable_dict))
def post(self): top_line = self.request.get("top-line") bottom_line = self.request.get("bottom-line") meme_url = self.request.get("template") data_dict = { "top_line": top_line, "bottom_line": bottom_line, "url": meme_url } meme1 = Meme(first_line=data_dict["top_line"], second_line=data_dict["bottom_line"], pic_type=data_dict["url"]) meme1.put() result_template = the_jinja_env.get_template('templates/result.html') self.response.write(result_template.render(data_dict))
def upload_memes(tags, url, all_tags): meme = Meme(image_url=url).put() meme_tag_objects = [] for tag in tags: if not tag in all_tags: all_tags[tag] = Tag(tag_name=tag).put() temp_meme_tag = Meme_and_Tag(meme=meme, tag=all_tags[tag]).put()
def __main__(): os.makedirs(conf['images_dir'], exist_ok=True) os.makedirs('vk_loader/loaded_ids', exist_ok=True) posts = get_new_posts() posts = filter(is_post_meme, posts) for post in posts: photo = post['attachments'][0]['photo'] ptr = len(PHOTO_URL_FIELDS) - 1 while ptr >= 0 and PHOTO_URL_FIELDS[ptr] not in photo: ptr -= 1 if ptr < 0: continue photo_url = photo[PHOTO_URL_FIELDS[ptr]] assert (photo_url.endswith('.jpg')) photo_id = get_random_id() try: print('loading', photo_id, photo_url) download(photo_url, conf['images_dir'] + photo_id + '.jpg') except IOError: print('Downloading/saving an image failed!') continue session.add(Meme(img=photo_id)) session.commit()
def post(self): """Handles POST requests for /memes endpoint Returns: dict -- Status or error message """ try: args = parser.parse_args() auth = args['meme_auth'] temp = args['temp'] is '1' or args['temp'] is None if auth != auth_key: return {'message': 'Bad meme authentication'}, 401 meme_url = args['url'] if not meme_url: return {'message': 'No empty memes'}, 401 existing = Meme.query.filter_by(url=meme_url).first() if not existing: meme = Meme(url=meme_url, temp=temp) db.session.add(meme) db.session.commit() return {'status': 'success'} return {'message': 'Meme already exists!'}, 401 except Exception as e: traceback.print_exc() return generic_400(e)
def seed_data(): fry_key = Image(name="fry_squint", image_file="fry.png").put() jc_key = Image(name="jackie_chan_wtf", image_file="jackie.png").put() tears_key = Image(name="tears_in_the_rain", image_file="tears.png").put() pika_key = Image(name="surprised_pikachu", image_file="surprised_pikachu.png").put() buzz_key = Image(name="buzz_everywhere", image_file="buzz_everywhere.jpg").put() roll_safe_key = Image(name="roll_safe", image_file="roll_safe.jpg").put() Meme(top_text="Not sure if meme app", bottom_text="or black hole", image=fry_key, creator="*****@*****.**", created_at=datetime.datetime(2018, 07, 23, 05, 23, 0, 0)).put() Meme(top_text="Meme app", bottom_text="doesn't save memes?", image=jc_key, creator="*****@*****.**", created_at=datetime.datetime(2018, 06, 23, 05, 23, 0, 0)).put() Meme(top_text="All these memes", bottom_text="lost like tears in the rain.", image=tears_key, creator="*****@*****.**", created_at=datetime.datetime(1984, 07, 23, 05, 23, 0, 0)).put()
def get(self): all_memes = Meme.query().fetch() the_variable_dict = {"all_memes": all_memes} all_memes_template = the_jinja_env.get_template( 'templates/all_memes.html') self.response.write(all_memes_template.render(the_variable_dict))
def get_last_meme_date(self, user_id): if self.cached_last_meme_date.get(user_id) is None: last_meme = Meme.get_last(user_id) if last_meme is not None: return last_meme.posted_at else: return datetime.utcnow() - timedelta(days=1) else: return self.cached_last_meme_date[user_id]
def populate_db(): with open('memes.json', 'r') as f: with app.app_context(): memes = json.loads(f.read()) for meme in memes: try: db.session.add(Meme(url=meme['url'], temp=False)) db.session.commit() except: pass
def post(self): user = users.get_current_user() image_name = self.request.get('image') image_key = Image.query(Image.name == image_name).fetch(1)[0].key Meme(top_text=self.request.get('top_text'), middle_text=self.request.get('middle_text'), bottom_text=self.request.get('bottom_text'), image=image_key, creator=user.user_id()).put() self.redirect('/')
def get_cached_meme_posted_at(chat_id, user_id): if not last_meme_posted_at_cache.get(chat_id): last_meme_posted_at_cache[chat_id] = dict() if not last_meme_posted_at_cache[chat_id].get(user_id): last_meme = Meme.get_last_meme(chat_id, user_id) if last_meme: last_meme_posted_at_cache[chat_id][user_id] = last_meme.posted_at else: last_meme_posted_at_cache[chat_id][user_id] = datetime.now( ) - timedelta(hours=1)
def get(self): memeStore = Meme.query().fetch() references = { "head1" : "Gallery", "memes" : memeStore } # self.response.headers["Content-Type"] = 'text/plain' # self.response.write("Here are some of my pictures: ") gallery_template = jinja_env.get_template('gallery.html') self.response.write(gallery_template.render(references))
def init(self): """Inicializa al bot""" self.log.info('"Alexis Bot" versión %s de %s.', __version__, __status__) self.log.info('Python %s en %s.', sys.version, sys.platform) self.log.info(platform.uname()) self.log.info('Soporte SQLite3 para versión %s.', sqlite3.sqlite_version) self.log.info('------') if 'default_memes' in self.config and len(self.config['default_memes']) > 0: self.log.info('Inicializando base de datos...') for meme_name, meme_cont in self.config['default_memes'].items(): Meme.get_or_create(name=meme_name, content=meme_cont) self.log.info('Conectando...') try: self.loop.create_task(posts_loop(self)) self.run(self.config['token']) except Exception as ex: self.log.exception(ex) raise
def get(self): memes = Meme.query().order(-Meme.created_at).fetch(10) if memes: latest_meme_key = memes[0].key.urlsafe() else: latest_meme_key = "" for meme in memes: meme.image_filename = meme.image.get().image_file start_template=jinja_current_directory.get_template( "templates/latestmemes.html") self.response.write(start_template.render({'memes': memes, 'latest_meme': latest_meme_key}))
def get(self): checkLoggedInAndRegistered(self) user = users.get_current_user() email_address = user.nickname() user_memes = Meme.query().filter(Meme.owner == email_address).fetch() the_variable_dict = {"user_memes": user_memes} user_memes_template = the_jinja_env.get_template( 'templates/user_memes.html') self.response.write(user_memes_template.render(the_variable_dict))
def get_idf_relevant_docs(query_postings): relevant_docs = {} idf = {} total_docs = Meme.objects.count() for term in query_postings: term_docs = 0 dict_entry = Entry.objects(id=term).only("total_documents").first() if dict_entry: term_docs = dict_entry.total_documents relevant_docs.update({ repr(meme.id): meme for meme in Meme.objects( __raw__={"postings." + term: { "$exists": "true" }}) }) idf[term] = log((total_docs - term_docs + L) / (term_docs + L), 10) return idf, relevant_docs.values()
def vote_handler(self, call: telebot.types.CallbackQuery): telegram_id = call.from_user.id chat_id = str(call.message.chat.id) msg_id = call.message.message_id mark = int(call.data) username = '******' + call.from_user.username if call.from_user.username else call.from_user.first_name user = User.get(chat_id, telegram_id) if not user: user = User(telegram_id, chat_id, username).save() meme = Meme.get_meme(chat_id, msg_id - 1) if meme and not Vote.is_voted(user.id, meme.id): Vote(user.id, meme.id, mark).save() print(user.username, 'voted', mark, flush=True) self.answer_callback_query(call.id, text='You voted') else: print(user.username, 'have tried to vote again', flush=True) self.answer_callback_query(call.id, text='You have already voted')
def post(self): user = users.get_current_user() # get current logged in user meme_key_string = self.request.get('meme_key') image_name = self.request.get('image') image_key = Image.query(Image.name == image_name).fetch(1)[0].key # get the key of the correct image by nickname if meme_key_string: meme = get_meme_from_key(meme_key_string) if meme.creator != user.user_id(): self.response.status = "403 Forbidden" return else: meme = Meme() meme.top_text=self.request.get('top_text') meme.middle_text=self.request.get('middle_text') meme.bottom_text=self.request.get('bottom_text') meme.image=image_key meme.creator=user.user_id() # grab the user ID from currently logged in user, store with Meme meme_key = meme.put() self.redirect('/view?meme_key=' + meme_key.urlsafe())
def get_callback_info(self, call): data = call.data user_id = call.from_user.id call_type = None mark = None is_voted = False back_text = ':)))))' if data.startswith('vote'): call_type = 'vote' mark = int(data.split('_')[-1]) meme = Meme.get_by_msg_id(call.message.message_id) user = User.get(user_id) if user.id == meme.user_id: back_text = 'Нельзя голосовать за свой мем' is_voted = False return { 'type': call_type, 'mark': mark, 'is_voted': is_voted, 'back_text': back_text } if self.save_vote(user_id, meme.id, mark): back_text = 'Вы проголосовали' is_voted = True else: back_text = 'Вы уже голосовали за этот мем' is_voted = False return { 'type': call_type, 'mark': mark, 'is_voted': is_voted, 'back_text': back_text }
def meme_handler(self, message: telebot.types.Message): telegram_id = message.from_user.id chat_id = str(message.chat.id) msg_id = message.message_id username = '******' + message.from_user.username if message.from_user.username else message.from_user.first_name get_cached_meme_posted_at(chat_id, telegram_id) if (datetime.utcnow() - last_meme_posted_at_cache[chat_id][telegram_id]).seconds > 10: if message.content_type != 'text': last_meme_posted_at_cache[chat_id][ telegram_id] = datetime.utcnow().replace(microsecond=0) user = User(telegram_id, chat_id, username).save_if_not_exists() meme = Meme(user.id, msg_id, chat_id).save() print('new meme', meme.id, flush=True) self.send_message(chat_id, 'Mark this meme', reply_to_message_id=msg_id, reply_markup=vote_keyboard()) else: if message.text.startswith('/'): self.command_handler(message)
def post(self): new_message = Meme(image_url=self.request.get('image_url'), caption=self.request.get('caption')) new_message.put() time.sleep(0.5) self.redirect('/')
def get(self): view_template = the_jinja_env.get_template('templates/view.html') memes_result = Meme.query().order().fetch() variable_dict = {"memes": memes_result} self.response.write(view_template.render(variable_dict))
def post(self): new_message = Meme(image_url=self.request.get("image_url"), caption=self.request.get("caption")) new_message.put() time.sleep(0.5) self.redirect("/")
def get(self): memes = Meme.query().order(-Meme.last_touch_date_time).fetch(20) self.response.out.write(template.render("templates/meme.html", {"memes": memes}))
def rose_meme_delete(self, a_meme): if not a_meme.from_datastore: raise endpoints.NotFoundException('Meme not Found') a_meme.key.delete() return Meme(image_url='Deleted')
def get(self): memes = Meme.query().order(-Meme.last_touch_date_time).fetch(20) self.response.out.write( template.render('templates/meme.html', {'memes': memes}))
def save_meme(self, user_id, file_type, file_id, msg_id): meme = Meme(user_id, file_type, file_id, msg_id).save() user = User.get(user_id) print(f'{user} have posted {meme}', flush=True)