def do_delete(self, argument): if argument == 'last': posts = Post.get_last(1) if len(posts) > 0: status_id = posts[0].status_id else: reply = "%s, I don't know any posts." % self._get_nick() if self.event.target() in self.bot.channels.keys(): self.conn.privmsg(self.event.target(), reply) else: conn.privmsg(nick, reply) return elif re.match('^[0-9]+$', argument): status_id = int(argument) else: raise CommandHandler.UsageError('remove') try: self.bot.posting_api.DestroyStatus( self.event.source(), status_id ) reply = "Status %d deleted" % status_id except IdenticaError, e: if str(e).find('Status deleted') >= 0: reply = "Status %d already deleted." % status_id Post.mark_deleted(status_id) else: reply = str(e)
def create_post(): post_body = json.loads(request.data) post = Post(text=post_body.get('text'), username=post_body.get('username')) db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 201
def create_post(user_id, community_id, body): post = Post(timestamp=datetime.datetime.now(), content=body.get("content"), edited=False, user_id=user_id, community_id=community_id) db.session.add(post) db.session.commit() return post.serialize()
def create_post(content, user_id, tag_id): new_post = Post( content=content, user_id=user_id, tag_id=tag_id ) db.session.add(new_post) db.session.commit() return new_post.serialize()
def create_post(): post_body = json.loads(request.data) post = Post( likes=0, text=post_body["text"], nickname=post_body["nickname"], workout=post_body["workout"], ) db.session.add(post) db.session.commit() return json.dumps({"success": True, "data": post.serialize()}), 200
def do_history(self, argument = None): if argument == None: posts = Post.get_last() else: if re.match('^[0-9]{4}-[0-1][0-9]-[0-9]{2}$',argument): posts = Post.get_by_day(argument) elif argument[0] == '@': posts = Post.get_by_user_id(argument[1:]) else: posts = Post.get_by_irc_id(argument) self._generate_history_replies(posts)
def create_post(user): post_body = json.loads(request.data) try: post = Post(text=post_body.get('text'), user_id=user) db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 201 except KeyError as e: return json.dumps({'success': False, 'data': 'Invalid input'}), 404
def get_tweets(self, username = None, limit = 20): if username == None: posts = Post.get_last(limit) else: posts = Post.get_by_user_id(username, limit) return map( lambda x: { 'poster': User.get_by_user_id(x.poster_id).ldap_id, 'status_id': x.status_id }, posts )
def create_post(): post_body = json.loads(request.data) title = post_body.get('title') body = post_body.get('body') author_id = post_body.get('author_id') user = User.query.filter_by(id=author_id).first() if not user: return json.dumps({'success': False, 'error': 'User not found'}), 404 post = Post(title=title, body=body, author_id=author_id) db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 201
def create_post(): """Append new post to list.""" post_body = json.loads(request.data) if 'username' in post_body and 'text' in post_body: post = Post(text=post_body.get('text'), username=post_body.get('username'), longitude=post_body.get('longitude'), latitude=post_body.get('latitude')) db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 200 return json.dumps({'success': False, 'error': 'Invalid POST body!'}), 404
def create_post(attraction_id): body = json.loads(request.data) attraction = Attraction.query.filter_by(id=attraction_id).first() if not attraction: return failure_response("Attraction not found") new_post = Post(netid=body.get("netid"), name=body.get( "name"), picture=body.get("picture"), description=body.get("description"), attraction_id=attraction_id) if not new_post.netid or not new_post.description: return failure_response("Missing required field") db.session.add(new_post) db.session.commit() return success_response(new_post.serialize(), 201)
def create_a_post(): # ensure the body is valid JSON try: post = json.loads(request.data) except ValueError: return json.dumps({ 'success': False, 'data': 'Error: Body not a valid JSON' }), 400 text = post.get("text") token = post.get("token") # ensure the body is in the expected format if len(list(post.keys())) != 2 or text is None\ or token is None: return json.dumps({ 'success': False, 'data': 'Error: Body not in the expected format' }), 400 # validate the user token with google oauth2 get_params = {'access_token': token} r = requests.get(url=AUTH_URL, params=get_params) data = r.json() try: google_id = data['id'] except KeyError: # token is invalid return json.dumps({ 'success': False, 'data': 'Error: Token is invalid' }), 400 print(google_id) user = User.query.filter_by(google_id=google_id).first() if user is None: # the user trying to create a post is not stored in our database. # i dont think this should ever happen (hopefully ?) print("No user exists with that google id") return json.dumps({ 'success': False, 'data': 'Error: User does not exist' }), 400 constructed_post = Post(text=text, nickname=user.nickname, upload_date=int(time.time()), user_id=user.id) db.session.add(constructed_post) db.session.commit() response = {'success': True, 'data': constructed_post.serialize()} return json.dumps(response), 201
def post_post(user_id): user = User.query.filter_by(id=user_id).first() if user is not None: post_body = json.loads(request.data) post = Post( title=post_body.get("title"), content=post_body.get("content"), username=post_body.get("username"), tags=post_body.get("tags"), user_id=post_body.get("user_id"), ) user.posts.append(post) db.session.add(post) db.session.commit() return json.dumps({"success": True, "data": post.serialize()}) return json.dumps({"success": False, "error": "User not found"}), 404
def _save_post(session, submission, image, created, subreddit_name): print "Saving post {}".format(submission.name) session.add(Post(name=submission.name, image_file_hash=image.file_hash, submitted=created, subreddit_name=subreddit_name)) session.flush()
def webhook_handler(): if request.method == "POST": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id text = update.message.text.encode('utf-8') date = datetime.datetime.now() - datetime.timedelta(hours=12) lastpostsent = LastPostSent().get_or_insert(str(chat_id), date=date) if text == '/reset': lastpostsent.date = datetime.datetime.now() - datetime.timedelta( hours=100) if lastpostsent.date < date: lastpostsent.date = date posts = Post.query(Post.date > lastpostsent.date).order( Post.date).fetch() for post in posts: text = u'%s' % str( post.date - datetime.timedelta(hours=3) ) + u'\n' + u'<a href="https://www.facebook.com/' + post.user_id + '">' + post.username + '</a>' + u'\n' + u'%s' % post.text + u'\n' + u'<a href="' + post.url + u'">Ir al post</a>' bot.sendMessage(chat_id=chat_id, text=text, parse_mode='HTML', disable_web_page_preview=True) postdate = post.date if len(posts) <= 0: bot.sendMessage(chat_id=chat_id, text=u'No hay nuevos posts. :/ Intenta mas tarde.') else: lastpostsent.date = postdate lastpostsent.put() return 'ok'
def create_post(): ''' file: ./documentation/create_post.yml ''' request_body = json.loads(request.data) # Code here checks for blank body requests / @beforerequests checks for None body requests if not request_body.get('text') == '' and not request_body.get( 'username') == '': post = Post(text=request_body.get('text'), username=request_body.get('username')) # Keep the two acts separate to reduce automatic commits to the server db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 201 return json.dumps({'success': False, 'error': 'invalid body format'}), 412
def run_scheduler(db, praw_id, subreddit_name, wiki_config_page, dry_run=False): reddit = praw.Reddit(praw_id) subreddit = reddit.subreddit(subreddit_name) wiki_config = subreddit.wiki[wiki_config_page].content_md config_items = list(yaml.load_all(wiki_config)) current_time = datetime.now() for config in config_items: posts = list(db.get_saved_post_data()) posts_by_id = {post.id: post for post in posts} next_post_time = datetime.strptime(config['first'], "%B %d, %Y %H:%M") repeat = parse_duration(config['repeat']) post = posts_by_id.get(config['id']) if post: while next_post_time < post.date: next_post_time += repeat if next_post_time > current_time: if dry_run: print "Not posting %s until %s" % (config['id'], next_post_time) continue post_template_data = {x['id']: "/" for x in config_items} post_template_data.update((post.id, "https://reddit.com/comments/%s/" % post.reddit_id) for post in posts) text = Template(config['text']).substitute(post_template_data) print "Submitting post %s" % (config['id']) if dry_run: print "I would submit the text: ", text else: reddit_post = subreddit.submit(title=render_template(config['title']), selftext=text, send_replies=False) reddit_post.mod.distinguish() if config.get('sticky', False): reddit_post.mod.sticky() db.save_post_data( Post(config['id'], current_time, reddit_post.id)) print "Saved, post is %s" % reddit_post.id
def create_post(): body = json.loads(request.data) if (body.get('title') is None): return failure_response('No title provided') if (body.get('price') is None): return failure_response('No price provided') if not logged_in(current_user): return failure_response('User not logged in') new_post = Post(title=body.get('title'), description=body.get('description'), seller=current_user.id, price=body.get('price'), image_data=body.get("image_data")) db.session.add(new_post) db.session.commit() return success_response(new_post.serialize(), 201)
def make_a_post(): post_body = json.loads(request.data) body_post = post_body.get('body') username = post_body.get('username') user = User.query.filter_by(username=username).first() if not user: return json.dumps({'success': False, 'error': 'user not found'}), 404 user_id = user.id newPost = Post(upvotes=0, body_post=body_post, time_stamp=datetime.now(), date=date.today(), user_id=user_id) db.session.add(newPost) db.session.commit() return json.dumps({'success': True, 'data': newPost.serialize()}), 201
def ranked_post_details(number_of_posts=None): db_posts = Post.select().where(Post.hidden == 0) post_details = [fields.marshal(post, post_fields) for post in db_posts] if number_of_posts: return post_details[number_of_posts:] else: return post_details
def post(user_id, **kwargs): post = Post(title=kwargs.get("title"), dateTime=datetime.datetime.now(), ingredients=kwargs.get("ingredients"), recipe=kwargs.get("recipe"), recipeTime=kwargs.get("recipeTime"), difficultyRating=kwargs.get("difficultyRating"), overallRating=0, priceRating=kwargs.get("priceRating")) user = User.query.filter_by(id=user_id).first() user.posts.append(post) db.session.add(post) db.session.commit() return post.serialize()
def new_post(title, content, points, user, location=None): if location is None: location = get_or_create_location(user, 'default', 'A catch-all location. Generic stuff here ... ') else: location = get_or_create_location(user, **location) insert_post = Post.create(title=title, content=content, points=points, created_by_id=user.pk, rank=1, location_id=location.pk) return insert_post
def _generate_history_replies(self, posts): shown_posts = 0 for post in posts: username = post.user.user_id try: status = self.bot.posting_api.GetStatus(post.status_id) created_at = post.created_at reply = "%s: %s (%s, id = %d)" % \ (username, status.text, created_at, status.id) self._do_private_reply(reply) shown_posts += 1 except IdenticaError, e: if str(e).find('Status deleted') >= 0: Post.mark_deleted(post.status_id, e) continue else: raise e
def setUp(self): super(TestPostImpl, self).setUp() setting = Setting() setting.initialize(os.path.join(current_dir, 'settings.cfg')) conn = Connection() conn.connect(setting.config) # initialize logger Logger.init(**setting.config.twisted.logging) Post.drop_collection() # Redis 초기화 self.redis = conn.redis self.redis.delete('current_post_id') self.fake = Factory.create()
def fake_post(self, count: int = 50): """构造虚拟文章""" for i in range(count): post_obj = Post( title=self.fake.sentence(), body=self.fake.text(2000), category=session.query(Category).get(random.randint(1, session.query(Category).count())) ) session.add(post_obj) session.commit()
def create_post(session, date): image_data = find_unused_image_data(session, date) if image_data: return Post(date=date, page_id=image_data['page_id'], image_url=image_data['scaled_url'], page_url=image_data['description_url'], title=image_data['title'].replace('File:', ''), created_at=datetime.now(), description=image_data['description'])
def create_seed_data(): new_user = User(google_id="106380710636073572230", nickname="littletree", join_date=int(time.time())) db.session.add(new_user) constructed_post = Post(text="I'm so sad", nickname="littletree", upload_date=int(time.time()), user_id=1) db.session.add(constructed_post) db.session.commit() return json.dumps({'success': True})
def make_post(): post_body = extract(request) if not all(post_body.get(i, '') for i in ['text', 'token', 'title']): return missing() if 'kind' not in post_body: return missing() kind = int(post_body['kind']) if kind not in [0, 1, 2]: return missing() if kind == 1 and ('group_size' not in post_body): return missing() if kind == 1 and ('role' not in post_body): return missing() uid = token_to_uid(post_body) if uid is None: return invalid_token() if not kind == 0: post_body.pop('course', None) if not kind == 1: post_body.pop('group_size', None) if not kind == 2: post_body.pop('skills', None) if kind == 1: role = clean_tags(post_body.get('role', )) if kind == 2: role = User.query.filter_by(uid=uid).first().role post = Post(uid=uid, title=post_body.get('title'), tags=clean_tags(post_body.get('tags', '')), role=role, text=post_body.get('text'), creation_time=time.time(), kind=int(post_body.get('kind')), course=clean_courses(post_body.get('course_id', None), 1), group_size=post_body.get('group_size', None), skills=clean_tags(post_body.get('skills', None))) activate(uid) db.session.add(post) db.session.commit() return json.dumps({'success': True, 'data': post.serialize()}), 201
def add_post(self, id_author, slug, title, content): post = Post(seq('posts'), id_author, slug, title, content) if not self.check_slug_aviability(slug): raise InvalidSlugException self.session.add(post) try: self.session.commit() except sqlalchemy.exc.IntegrityError: self.session.rollback()
def form(): if request.method == 'POST': post_path = get_unique_post_path(post_header=request.form['header']) db_session.add( Post( header=request.form['header'], signature=request.form['signature'], body=request.form['body'], published=datetime.date.today(), path=post_path, ), ) db_session.commit() session[post_path] = post_path session.permanent = True return redirect(url_for('show_post', post_path=post_path)) return render_template('form.html')
def get_post_info(self): parser = fromstring(self.driver.page_source) instagram_id_box = parser.xpath( '/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div[1]/a' ) instagram_id = instagram_id_box[0].text location_info_box = parser.xpath( '/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[2]/div[2]/a' ) location_info = location_info_box[0].text contents_box = parser.xpath( '/html/body/div[1]/section/main/div/div[1]/article/div[3]/div[1]/ul/div/li/div/div/div[2]/span' ) contents = contents_box[0].text_content() tags_box = parser.xpath( '/html/body/div[1]/section/main/div/div[1]/article/div[3]/div[1]/ul/div/li/div/div/div[2]/span/a' ) tags = ','.join([tag.text for tag in tags_box]) post = Post(location=location_info, contents=contents, tags=tags, instagram_id=instagram_id) return post
from db import Asset, Attraction, Post, Comment, CATEGORIES from flask import Flask from flask import request app = Flask(__name__) db_filename = "hack_challenge.db" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///%s" % db_filename app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_ECHO"] = False db.init_app(app) with app.app_context(): db.create_all() Attraction.initialize() Post.initialize() def success_response(data, code=200): return json.dumps({"success": True, "data": data}), code def failure_response(message, code=404): return json.dumps({"success": False, "error": message}), code # retrieve all categories @app.route("/categories/") def get_categories(): return success_response(CATEGORIES) # retrieve a category
def render_wall(response, wall_id): for post in Post.iter(wall=wall_id): author = User.get(id=post.user) response.write("<hr><h4>%s</h4><p>%s</p>" % (author.fullname(), post.msg))
from db import Post p = Post(tag='测试', time="2020-12-26", author="测试", content="#第一个Markdown测试文章", title="测试MD文章") p.save() print('DONE')
def DestroyStatus(self, source, id, *args, **kwargs): Post.delete(id, source) return super(IdenticaApi,self).DestroyStatus(id, *args, **kwargs)
def edit_post(pk, title, content, points): post = Post.update(title=title, content=content, points=points).where(Post.pk == pk) return post.execute()
def change_rank(pk, change): post = Post.update(rank=Post.rank + change).where(Post.pk == pk) return post.execute()
def delete_post(pk): post = Post.update(hidden=1).where(Post.pk == pk) _ = delete_post_votes(pk) return post.execute()
def delete(self, pk): try: _ = Post.get(Post.created_by == current_user.pk, Post.pk == pk) except Post.DoesNotExist: return {'error': 'You do not have permission to do that. '} return db_mods.delete_post(pk)
def submitPost(): meta = {"tags":request.form.get("tags").split(','), "user":"******"} post = Post(request.form.get("title"), request.form.get("body"), meta) postId = db.addPost(post) return redirect(f"/post/{postId}", code=302)
def tearDown(self) -> None: Post.drop_collection()
def find_post(pk): return Post.get(Post.pk == pk)
import csv import datetime from db import User, db_session, Post posts_list=[] u=User with open('blog.csv', 'r' , encoding='utf-8' ) as f: fields = ['title', 'image', 'published','content','email','first_name','last_name'] reader = csv.DictReader(f, fields, delimiter=';') for row in reader: row['published']=datetime.datetime.strptime(row['published'], '%d.%m.%y %H:%M') author=u.query.filter(User.email==row['email']).first() row['user_id']=author.id posts_list.append(row) for post_data in posts_list: post=Post(post_data['title'],post_data['image'], post_data['published'],post_data['content'], post_data['user_id']) db_session.add(post) db_session.commit()
def put(self, pk): try: _ = Post.get(Post.created_by == current_user.pk, Post.pk == pk) except Post.DoesNotExist: return {'error': 'You do not have permission to do that. '} return db_mods.edit_post(pk, request.form['title'], request.form['content'], request.form['points'])