def import_db(file): dbfile = open(file) heads = dbfile.readline().strip('\r\t\n').split('\t') table = heads[0] schemas = heads[1:] for line in dbfile: fields = line.strip('\r\t\n').split('\t') if len(fields) == 0 or fields[0] == '': continue options = defaultdict(str) for i in range(min(len(fields), len(heads) - 1)): options[heads[i + 1]] = fields[i] print options if table == 'User': user = User.query.filter_by(username=options['username']).first() if user == None: user = User() entry = user.assign(**options) db.session.add(entry) elif table == 'Post': post = Post.query.filter_by(pid=options['pid']).first() if post == None: post = Post() entry = post.assign( **options) #unpack dictionary into keyword arguments db.session.add(entry) elif table == 'EntityStream': entitystream = EntityStream.query.filter_by( eid=options['eid']).first() if entitystream == None: entitystream = EntityStream() entry = entitystream.assign(**options) if options['suggestion']: for s in options['suggestion'].split('|'): searchkey = SearchKey.query.filter_by(word=s).first() if searchkey == None: searchkey = SearchKey(s) # print searchkey.word entry.suggestion.append(searchkey) db.session.add(entry) db.session.commit()
def posts(username): form = PostForm() # query database for proper person person = User.query.filter_by(username=username).first() # when form is submitted append to posts list, re-render posts page if form.validate_on_submit(): tweet = form.tweet.data post = Post(tweet=tweet, user_id=current_user.id) # add post variable to database stage, then commit db.session.add(post) db.session.commit() return redirect(url_for('posts', username=username)) return render_template('posts.html', person=person, title='Posts', form=form, username=username)
def profile(username): form = PostForm() if form.validate_on_submit(): # step 1: create an instance of the db model post = Post(tweet=form.tweet.data, user_id=current_user.id) # step 2: add the record to the stage db.session.add(post) # step 3: commit the stage to the db db.session.commit() return redirect(url_for('profile', username=username)) # pass in user via the username taken in user = User.query.filter_by(username=username).first() return render_template('profile.html', form=form, user=user, title='Profile')
def post_new_app(): if request.method == 'GET': posts = Post.query.all() data = [] for post in posts: each_post = {} each_post['id'] = str(post.id) each_post['article_title'] = post.title each_post['content'] = post.content data.append(each_post) # convert to json format data_json = json.dumps(data, ensure_ascii=False) return data_json post = Post(title=request.json['title'], content=request.json['content'], user_id=1) db.session.add(post) db.session.commit() return 'post successful'
def shop(): form = BlogForm() # topics = Post(topic_id=0) # db.session.add(topics) #db.session.commit() posts = Post.query.all() if form.validate_on_submit(): if current_user.is_authenticated: post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() # a = Post.query.order_by(Post.topic_id.desc()).all() # for updated in a: # b = str(updated) # if len(b) > 4: # print("this means it doesn;t work kinda idk") # updated_list.append(updated) # flash('Your post is now live!') return redirect(url_for('shop')) else: return redirect(url_for('signup')) return render_template('shop.html', form=form, posts=posts)
def index(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, timestamp=datetime.datetime.utcnow(), author=g.user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) posts = [{ 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' }] return render_template('index.html', title='Home', form=form, posts=posts)
def user(username): user = User.query.filter_by(username=username).first_or_404() page = request.args.get('page', 1, type=int) postform = PostForm() if postform.validate_on_submit(): post = Post(body=postform.post.data, author=current_user) db.session.add(post) db.session.commit() flash(_('Your post is now live!')) return redirect(url_for('main.user', username=current_user.username)) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('main.user', username=user.username, page=posts.next_num) \ if posts.has_next else None prev_url = url_for('main.user', username=user.username, page=posts.prev_num) \ if posts.has_prev else None return render_template('user.html', user=user, posts=posts.items, next_url=next_url, prev_url=prev_url, postform=postform)
def index(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') """ After we process the form data, we end the request by issuing a redirect to the homepage. It's standard practice to respond to a POST request generated by a web form submission with a redirect. It helps mitigate an annoyance with how the refresh command is implemented in web browsers. When you refresh a page, the web browser is just re-issuing the last request. If a POST request with a form submission returns a regular response, then a refresh will re-submit the form. Since this behaviour is unexpected the browser is going to ask the user to confirm the duplicate submission. If a POST request is answered with a redirect, the browser is now instructed to send a GET request to grab the page indicated in the redirect, so the latest request is no longer a POST, its a GET. And the refresh command as a result, works in a more predictable way """ return redirect(url_for('index')) # return render_template('index.html', title='Home', user=user) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def regra(): form = TaxaForm() if form.validate_on_submit(): sw_id = current_user.sw_id.encode('ascii') print type(sw_id) while (len(sw_id) != 16): sw_id = '0' + sw_id print(sw_id) tx = form.taxa.data tx = tx + '000000' #set_queue(tx,sw_id) post = Post(body=form.taxa.data, author=current_user) db.session.add(post) db.session.commit() r = set_meter(tx, sw_id, current_user.id) print(r) l = set_rule(current_user.sw_port, current_user.id, sw_id) print(l) flash("Alteracao realizada com sucesso") return render_template('regra.html', title='Regra', form=form)
def profile(username): form = PostForm() if form.validate_on_submit(): #step 1: Create an instance of the db model post = Post(tweet=form.tweet.data, user_id=current_user.id) #add record db.session.add(post) #like git commit - adds to the database db.session.commit() return redirect(url_for('profile', username=username)) #retrieve all posts and pass in to view #pass in user via the username taken in user = User.query.filter_by(username=username).first() return render_template('profile.html', form=form, user=user, title='Profile')
def post(current_user, user_id): """Creates post for currently logged in user with id <user_id>""" form = Upload() user = User.query.filter_by(id=user_id).first() if user == None: return jsonify({'error': 'This user does not exist'}) if request.method == 'POST' and form.validate_on_submit(): image = request.files['image'] caption = form.caption.data filename = secure_filename(image.filename) post = Post(userid=user_id, photo=filename, caption=caption, created_on=current_date()) db.session.add(post) db.session.commit() image.save('app/static/images/' + filename) return jsonify({'message': 'Post successfully created'}) return jsonify_errors(form_errors(form))
def index(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) page = request.args.get('page', 1, type=int) # line 22 should be changes as just shows your own followers. Alternatively remove this functionality? posts = current_user.posts.paginate(page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) \ if posts.has_prev else None return render_template("index.html", title='Home Page', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): # step 75 in the Workflow form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash("You post has been submitted") # POST/redirect/GET pattern return redirect(url_for("index")) # user = {"username": "******"} # posts = [ # {"author": {"username": "******"}, "body": "Mufasani man oldirganman"}, # {"author": {"username": "******"}, "body": "Shut up, you stupid donkey!"}, # ] # step 75 in the Workflow # posts = current_user.followed_posts().all() # step 83 in the Workflow - modify the step 75 page = request.args.get("page", 1, type=int) posts = current_user.followed_posts().paginate( page, app.config["POSTS_PER_PAGE"], False ) # step 85 in the Workflow next_url = url_for("index", page=posts.next_num) if posts.has_next else None prev_url = url_for("index", page=posts.prev_num) if posts.has_prev else None return render_template( "index.html", title="Home", posts=posts.items, form=form, next_url=next_url, prev_url=prev_url, ) # read the step 39
def test_comments(self): r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) u2 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() post = Post(body='body of the post', author=u1) db.session.add(post) db.session.commit() response = self.client.post('/api/v1/posts/{}/comments/'.format(post.id), headers=self.get_api_headers('*****@*****.**', '12345'), data=json.dumps({'body': 'Good [post](http://example.com)!'})) self.assertEqual(response.status_code, 201) json_response = json.loads(response.get_data(as_text=True)) url = response.headers.get('Location') print(url) print(json_response) self.assertIsNotNone(url) self.assertEqual(json_response['body'], 'Good [post](http://example.com)!') self.assertEqual(re.sub('<.*?>', '', json_response['body_html']), 'Good post!') response = self.client.get(url, headers=self.get_api_headers('*****@*****.**', '123456')) self.assertEqual(response.status_code,200) json_response = json.loads(response.get_data(as_text=True)) self.assertEqual('http://localhost'+json_response['url'],url) self.assertEqual(json_response['body'],'Good [post](http://example.com)!') comment = Comment(body='Thank you!',author=u1,post=post) db.session.add(comment) db.session.commit() response = self.client.get('/api/v1/posts/{}/comments/'.format(post.id), headers=self.get_api_headers('*****@*****.**', '12345')) self.assertEqual(response.status_code,200) json_response = json.loads(response.get_data(as_text=True)) self.assertIsNotNone(json_response.get('comments')) self.assertEqual(json_response.get('count',0),2)
async def create( data: PostCreateUpdateModel, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """ Creates a new Post :param data: must be PostCreateModel comparable :param current_user: Current authenticated user :param db: Session instance :return: 201 Created """ try: post = Post( text=data.text, cover=data.cover, author_id=current_user.id, preview_text=data.preview_text, title=data.title ) db.add(post) db.commit() for tag_id in data.tags: post_tag = PostTag( post_id=post.id, tag_id=tag_id ) db.add(post_tag) db.commit() return Response(status_code=201) except Exception as e: db.rollback() raise HTTPException(status_code=500, detail=str(e))
def post(self): """ Add new post """ args = article_args.parse_args() img = Image.query.filter_by(id=args['img_id']).first() category = Category.query.filter_by(name=args['category']).first() if not category: category = Category(name=args['category']) p = Post(title=args['title'], description=args['desc'], category=category, body=args['body'], author=current_user, img=img) try: db.session.add(p) db.session.commit() except Exception as e: db.session.rollback() raise Conflict return p.to_dict()
def explore(): """Funkcja wyświetlająca strone główną aplikacji wraz z postami wszystkich użytkowników.""" form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Succesfully added a post!') return redirect(url_for('explore')) page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('explore', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('explore', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title=_("Explore"), form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def test_post_edit(self): user = User(email="*****@*****.**", username="******", password="******") user.confirmed = True post = Post(title="1234", body="none") post.user = user db.session.add(user) db.session.add(post) db.session.commit() response = self.client.post( url_for("auth.login"), data={"identifier": "test", "password": "******"}, follow_redirects=True, ) self.assertTrue("test" in response.get_data(as_text=True)) response = self.client.post( url_for("main.post_edit", postid=post.id), data={"title": "1234", "body": "test_edit"}, follow_redirects=True, ) self.assertTrue("test_edit" in response.get_data(as_text=True))
def index(): form = EditPostForm() if request.method=="POST": post=Post( body=request.form.get('body'), author=current_user._get_current_object() ) db.session.add(post) return redirect(url_for('main.index')) show_followed=False if current_user.is_authenticated: show_followed=bool(request.cookies.get('show_followed','')) if show_followed: query=current_user.followed_posts else: query=Post.query page=request.args.get('page',default=1,type=int) pagination=query.order_by(Post.timestamp.desc()).paginate( page,current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False ) posts=pagination.items return render_template('index.html',form=form,posts=posts,pagination=pagination,show_followed=show_followed)
def index(): print(app.config) form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title='Home Page', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == "UNKNOWN" or len(language) > 5: language = "" post = Post(body=form.post.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash(_("Your post is now live!")) return redirect(url_for("main.index")) page = request.args.get("page", 1, type=int) posts = current_user.followed_posts().paginate( page, current_app.config["POSTS_PER_PAGE"], False) next_url = url_for("main.explore", page=posts.next_num) \ if posts.has_next else None prev_url = url_for("main.explore", page=posts.prev_num) \ if posts.has_prev else None return render_template("index.html", title=_("Home Page"), form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def myaccount(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Din post är skickat!') return redirect(url_for('myaccount')) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('myaccount', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('myaccount', page=posts.prev_num) \ if posts.has_prev else None return render_template('myaccount.html', drop_down_cats=drop_down_cats, title='Mitt Konto', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body=form.post.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash(_('Your post is now live!')) return redirect(url_for('main.index')) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('main.index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('main.index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title=_('Home'), form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def newpost(): form = PostForm() if form.validate_on_submit(): pic = None if form.image.data: picture_file = save_picture(form.image.data) final_pic = picture_file pic = final_pic post = Post(title=form.title.data, content=form.content.data, author=current_user, image=pic) db.session.add(post) db.session.commit() flash('Your post has been published!', 'success') return redirect(url_for('main.home')) myposts = Post.query.order_by(Post.posted_date.desc()) return render_template('newpost.html', title='New Post', form=form, legend='New Post', myposts=myposts)
def user(username): user = User.query.filter_by(username=username).first_or_404() posts = user.followed_posts() form = LogActivity() form2 = EmptyForm() #posts = current_user.followed_posts().all() if form.validate_on_submit(): post = Post(action=form.action.data, item=form.item.data, body=form.comment.data, author=current_user) post.calculate_points() if form.action.data != 'have something else to share': if post.points == 1: points_str = 'point' else: points_str = 'points' if post.item is None or len(form.item.data) == 0: post.body = ' says: "I {}." They have earned {} {}!'.format( post.action.lower(), str(post.points), points_str) else: post.body = ' says: "I {} {}." They have earned {} points!'.format( post.action.lower(), post.item, str(post.points)) if form.comment.data is not None or len(form.comment.data) > 0: post.body = post.body + '\n' + form.comment.data post.timestamp = datetime.now().strftime("%H:%M:%S %d-%m-%Y ") user.points += post.points db.session.add(post) db.session.commit() form = LogActivity() return redirect(request.url) return render_template("user.html", user=user, posts=posts, form=form, points=user.points)
def index(self): if request.method == 'POST': title = request.form['title'] body = request.form['body'] try: post = Post(title=title, body=body) db.session.add(post) db.session.commit() except Exception as ex: cprint("RED", "Error: Post insert tk db. ex: {}".format(ex)) return redirect(url_for('admin.index')) form = PostForm() q = request.args.get('q') page = request.args.get('page') if page and page.isdigit(): page = int(page) else: page = 1 if q: posts = Post.query.filter( Post.title.contains(q) | Post.body.contains(q)) # .all() else: # posts = Post.query.all() posts = Post.query.order_by(Post.created.desc()) pages = posts.paginate(page=page, per_page=7) return render_template("admin/home.html", pgname="Home", company=Configuration.HTML_TITLE_COMPANY, url_prefix='/{}'.format('admin'), form=form, pages=pages)
def index(): form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body=form.post.data, body2=form.post2.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('index')) posts = [{ 'author': { 'username': '******' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'username': '******' }, 'body': 'The Avengers movie was so cool!' }] page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) flash( 'I guessed that this language is {} and has a length of {}. The locale is {}' .format(language, len(language), g.locale)) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body=form.post.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash(_('Your post is now live!')) '''It is a standard practice to respond to a POST request generated by a web form submission with a redirect. This helps mitigate an annoyance with how the refresh command is implemented in web browsers. The browser is now instructed to send a GET request to grab the page indicated in the redirect.''' return redirect(url_for('index')) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title=_('Home'), form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): # Add post to DB if this is a post form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body=form.post.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash(_('Your post is now live!')) return redirect(url_for('index')) # Get the page of posts page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) # Generate next and previous page urls if posts.has_next: next_url = url_for('index', page=posts.next_num) else: next_url = None if posts.has_prev: prev_url = url_for('index', page=posts.prev_num) else: prev_url = None return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def truy_xuat_gia_chu(username): thong_tin_gia_chu = chuoi_HTML_gia_chu(username) # Gửi thông tin liên hệ ghi nhận lên web user = UserDb.query.filter_by(username=username).first() form_contact = PostForm() if request.method == "POST": post = Post() post.user_id = user.id post.body = form_contact.post.data post.title = user.username try: db.session.add(post) db.session.commit() flash( 'Nội dung góp ý đã cập nhật. Vui lòng xem mục "Câu hỏi liên quan" !' ) except Exception as e: flash('Phát sinh lỗi {}'.format(e)) db.session.rollback() #return redirect(url_for('index')) elif request.method == "GET": form_contact.username.data = user.username form_contact.email.data = user.email # Hiển thị ngày tháng năm ngay_thang_nam = date.today().strftime('%d/%m/%Y') #Hiển thị các bài post liên quan đến user user_id = user.id posts = xuat_post(user_id) return render_template('auth/user.html', form_contact=form_contact, Thong_Tin_Gia_Chu=Markup(thong_tin_gia_chu), NgayThangNam=ngay_thang_nam, POST=posts)