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 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(): 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(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 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(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 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 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 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_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 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 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 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 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 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 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 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 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 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 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
db.init_app(app) with app.app_context(): db.drop_all() db.create_all() user_dao.create_user('*****@*****.**', '1234') user_dao.create_user('*****@*****.**', '1234') user_dao.create_user('*****@*****.**', '5678') user_dao.create_user('*****@*****.**', '5678') relation1 = Friendship(user_1_id=1, user_2_id=2, status=2, action_user=2) relation2 = Friendship(user_1_id=1, user_2_id=3, status=2, action_user=3) relation3 = Friendship(user_1_id=1, user_2_id=4, status=1, action_user=1) db.session.add(relation1) db.session.add(relation2) db.session.add(relation3) post1 = Post(text='User 1 first post', user_id=1) db.session.add(post1) post2 = Post(text='User 2 first post', user_id=2) db.session.add(post2) post3 = Post(text='User 3 first post', user_id=3) db.session.add(post3) post4 = Post(text='User 4 first post', user_id=4) db.session.add(post4) db.session.commit() def extract_token(request): auth_header = request.headers.get('Authorization') if auth_header is None: return False, json.dumps({'error': 'Missing authorization header.'})
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)
from db import Post p = Post(tag='测试', time="2020-12-26", author="测试", content="#第一个Markdown测试文章", title="测试MD文章") p.save() print('DONE')
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()
import csv import datetime from db import db_session, Post, User 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"]) # см def init db_session.add(post) db_session.commit()