Beispiel #1
0
async def index(request):
    summary = "This is the test sumary."
    #users=await User.findAll()
    blogs = [
        Blog(id='1',
             name='test Blog',
             summary=summary,
             create_at=time.time() - 120),
        Blog(id='2',
             name='something new',
             summary=summary,
             create_at=time.time() - 3600),
        Blog(id='3',
             name='learn Switf',
             summary=summary,
             create_at=time.time() - 7200)
    ]

    cookie_str = request.cookies.get(COOKIE_NAME)
    user = ''
    if cookie_str:
        if 'deleted' in cookie_str:
            user = ''
        else:
            user = await cookie2user(cookie_str)

    return {'__template__': 'blogs.html', 'blogs': blogs, 'user': user}
Beispiel #2
0
async def index(request):
    """首页"""
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    blogs = [
        Blog(id='1',
             name='Test Blog',
             summary=summary,
             created_at=time.time() - 120),
        Blog(id='2',
             name='Something New',
             summary=summary,
             created_at=time.time() - 3600),
        Blog(id='3',
             name='Learn Swift',
             summary=summary,
             created_at=time.time() - 7200)
    ]
    user = None
    try:
        cookie_str = request.cookies.get(COOKIE_NAME)
        if 'deleted' not in cookie_str:
            user = await cookie2user(cookie_str)
    except:
        pass
    return {'__template__': 'blogs.html', 'blogs': blogs, '__user__': user}
Beispiel #3
0
def index(request):
    # users = await User.findAll()
    # return {
    #     '__template__' : 'test.html',
    #     'users': users
    # }
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    blogs = [
        Blog(id='1',
             name='Test Blog',
             summary=summary,
             created_at=time.time() - 120),
        Blog(id='2',
             name='Something New',
             summary=summary,
             created_at=time.time() - 3600),
        Blog(id='3',
             name='Learn Swift',
             summary=summary,
             created_at=time.time() - 7200)
    ]
    return {
        '__template__': 'blogs.html',
        'blogs': blogs,
        # '__user__':request.__user__
    }
Beispiel #4
0
async def test_index():
    """ test_page: show index(blogs)"""
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore' \
              ' et dolore magna aliqua.'
    blogs = [Blog(id="tsb1", name="Blog Test 1", summary=summary, createtime=time.time() - 10),
             Blog(id="tsb2", name="Blog Test 2", summary=summary, createtime=time.time() - 100),
             Blog(id="tsb3", name="Blog Test 3", summary=summary, createtime=time.time() - 3900),
             Blog(id="tsb4", name="Blog Test 4", summary=summary, createtime=time.time() - 86400),
             Blog(id="tsb5", name="Blog Test 5", summary=summary, createtime=time.time() - 86400 * 10)]
    return dict(blogs=blogs)
Beispiel #5
0
async def index(request):
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    blogs = [
        Blog(id='1', name='Test Blog', summary=summary, created_at=time.time() - 120),
        Blog(id='2', name='Something New', summary=summary, created_at=time.time() - 3600),
        Blog(id='4', name='Learn Swift', summary=summary, created_at=time.time() - 7200)
    ]
    return {
        '_template': 'blogs.html',
        'blogs': blogs
    }
Beispiel #6
0
def create_post():
    if request.method == 'POST':
        author = User.query.filter_by(username=session['user']).first()
        blog_title = request.form['blog-title']
        blog_body = request.form['blog-body']
        title_error = ''
        body_error = ''

        if not blog_title:
            title_error = "All posts need titles, give it one!"

        if not blog_body:
            body_error = "You can't have a blog post without a post, get writing!"

        if not title_error and not body_error:
            new_post = Blog(blog_title, blog_body, logged_in_user())
            db.session.add(new_post)
            db.session.commit()
            return redirect('/blog?id={}'.format(new_post.id))
        else:
            return render_template('newpost.html',
                                   title="New Post",
                                   title_error=title_error,
                                   body_error=body_error,
                                   blog_title=blog_title,
                                   blog_body=blog_body)
    return render_template('newpost.html', title='New Post')
Beispiel #7
0
def newpost():

    if request.method == 'POST':
        valid = True
        title_error = ''
        body_error = ''

        title = request.form['title']
        body = request.form['body']
        current_user = User.query.filter_by(username=session['username']).first()

        #check if both title and body are there
        if not title:
            title_error = "Pleae fill in a title"
            valid = False
        if not body:
            body_error = "Pleae fill in a body"
            valid = False


        if valid:
            #add and commit title and body in a new post if valid 
            new_post = Blog(title, body, current_user)
            db.session.add(new_post)
            db.session.commit()
            return redirect('/blog?post_id={0}'.format(new_post.id))
        else: 
            return render_template('newpost.html', 
                                           title_error=title_error,
                                           body_error=body_error)


    return render_template('newpost.html')
Beispiel #8
0
async def api_create_blog(request, *, title, summary, content, cat_name):
    if request.__user__ is None or not request.__user__.admin:
        raise APIPermissionError('Only admin can do this!')
    if not title or not title.strip():
        raise APIValueError('title', 'Title can not be empty.')
    if not summary or not summary.strip():
        summary = content.strip()[:200]
    elif len(summary.strip()) > 200:
        raise APIValueError('summary',
                            'Length of summary can not be larger than 200.')
    if not content or not content.strip():
        raise APIValueError('content', 'Content can not be empty.')
    if not cat_name.strip():
        cat_id = None
    else:
        cats = await Category.findAll(where='name=?', args=[cat_name.strip()])
        if (len(cats) == 0):
            raise APIValueError('cat_name',
                                'cat_name is not belong to Category.')
        cat_id = cats[0].id
    blog = Blog(user_id=request.__user__.id,
                user_name=request.__user__.name,
                user_image=request.__user__.image,
                title=title.strip(),
                summary=summary.strip(),
                content=content.strip(),
                cat_id=cat_id,
                cat_name=cat_name.strip())
    await blog.save()
    return blog
Beispiel #9
0
async def api_create_blog(request, *, name, summary, content, selectedTags):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError("name", "name cannot be empty.")
    if not summary or not summary.strip():
        raise APIValueError("summary", "summary cannot be empty.")
    if not content or not content.strip():
        raise APIValueError("content", "content cannot be empty.")
    blog = Blog(
        user_id=request.__user__.id,
        user_name=request.__user__.name,
        user_image=request.__user__.image,
        name=name.strip(),
        summary=summary.strip(),
        content=content.strip(),
    )
    await blog.save()
    for selectedTag in selectedTags:
        if selectedTag["key"]:
            blog_tag = BlogTag(blog_id=blog.id, tag_id=selectedTag["key"])
            await blog_tag.save()
        else:
            tag = Tag(name=selectedTag["value"])
            await tag.save()
            blog_tag = BlogTag(blog_id=blog.id, tag_id=tag.id)
            await blog_tag.save()
    return blog
Beispiel #10
0
def new_post():
    title_header = 'Add Blog Post'
    user = User.query.filter_by(name=session['username']).first()

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        validation = validate_post(title, body)

        if validation == True:
            new_blog = Blog(title, body, user)
            db.session.add(new_blog)
            db.session.commit()
            return redirect('/blog?id={0}'.format(new_blog.id))
        else:
            return render_template('new_post.html',
                                   base_title=title_header,
                                   base_header=title_header,
                                   title=title,
                                   title_err=validation['title_err'],
                                   body=body,
                                   body_err=validation['body_err'])
    else:
        return render_template('new_post.html',
                               base_title=title_header,
                               base_header=title_header)
Beispiel #11
0
def get_blog(parameters, blog_id):
    response = {'http_status': 404}
    blog = Blog(blog_id)
    if not blog.exists:
        return response
    response.update(blog.__dict__)
    response['http_status'] == 200
    return response
Beispiel #12
0
 def post(self):
     sender = self.request.GET.get("from", "")
     if sender == blogSystem.postEmailAddr:
         msg = Message(self.request.body)
         blogEntity = Blog(title=msg.data["email-subject"],
                           content=msg.data["email-text"],
                           createTimeStamp=datetime.now())
         blogEntity.publish()
     return
Beispiel #13
0
def create_blog(title, overview):
    """Create and return a new blog."""

    blog = Blog(title=title, overview=overview)

    db.session.add(blog)
    db.session.commit()

    return blog
Beispiel #14
0
def add_blog(title, picture, name, text, day, month):
    blog_object = Blog(title=title,
                       picture=picture,
                       name=name,
                       text=text,
                       day=day,
                       month=month)
    session.add(blog_object)
    session.commit()
Beispiel #15
0
async def index(request):
    summary = 'long long ago, there is a bird, her name is BuGu. One day, she fly to my dream.'

    blogs = [
        Blog(id='1',
             name="Test Blog",
             summary=summary,
             created_at=time.time() - 180),
        Blog(id='2',
             name="Somethind New",
             summary=summary,
             created_at=time.time() - 60 * 60 * 5),
        Blog(id='3',
             name="Learn Python",
             summary=summary,
             created_at=time.time() - 60 * 60 * 24 * 3)
    ]

    return {'__template__': 'blogs.html', 'blogs': blogs}
def api_create_blog(request,*,name,summary,content):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name','name cannot be empty.')
    if not summary or not summary.strip():
        raise APIValueError('summary','summary cannot be empty.')
    if not  content or not content.strip():
        raise APIValueError('conten','content cannot be empty.')
    blog = Blog(user_id = request.__user__.id,user_name = request.__user__.name,user_image=request.__user__.image,name =name.strip(),content=content.strip(),summary = summary.strip())
    yield from blog.save()
    return blog
Beispiel #17
0
async def api_create_blog(request, *, title, summary, content):
	check_admin(request)
	if not title or not title.strip():
		raise APIValueError('title', 'title cannot be empty')
	if not summary or not summary.strip():
		raise APIValueError('summary', 'summary cannot be empty')
	if not content or not content.strip():
		raise APIValueError('content', 'content cannot be empty')
	blog =  Blog(user_id=request.__user__.id, user_name=request.__user__.name, avatar_url=request.__user__.avatar_url, title=title.strip(), summary=summary.strip(), content=content.strip())
	await blog.save()
	return blog
Beispiel #18
0
async def api_create_blog(request, name, summary, content):
    """ create an article"""
    _user = check_permission(request)
    name, summary, content = check_blog_content(name, summary, content)
    # insert new blog
    blog = Blog(user_id=_user.id, user_name=_user.name, user_image=_user.image, name=name, summary=summary,
                content=content)
    rs = await blog.insert()
    if rs != 1:
        logging.error('insert blog error: %s rows affected.' % rs)
        raise ApiError('create-blog:failed', msg='insert blog failed.')
    return dict(blog=blog)
Beispiel #19
0
async def api_update_blog(request, name, summary, content, id, **kwargs):
    """ update an article """
    check_permission(request)
    name, summary, content = check_blog_content(name, summary, content)
    # update
    rs = await Blog.update_by(set_dict=dict(name=name, summary=summary, content=content), where_dict=dict(id=id))
    if rs != 1:
        logging.error('update blog error: %s rows affected.' % rs)
        raise ApiError('update-blog:failed', msg='blog does not exist!')
    # return same blog
    blog = Blog(id=id, name=name, summary=summary, content=content, **kwargs)
    return dict(blog=blog)
Beispiel #20
0
def create_form():
    """"Create a post and add to database"""
    form = BlogForm()
    if form.validate_on_submit():
        post = Blog(title=form.title.data,
                    description=form.description.data,
                    date=form.date.data)
        db.session.add(post)
        db.session.commit()
        return redirect('/')
    return render_template("create_form.html",
                           title="Create a Post",
                           form=form)
def api_create_blog():
    i = ctx.request.input(name='', summary='', content='')
    name = i.name.strip()
    summary = i.summary.strip()
    content = i.content.strip()

    user = ctx.request.user
    blog = Blog(user_id=user.id,
                user_name=user.name,
                name=name,
                summary=summary,
                content=content)
    blog.insert()
    return blog
Beispiel #22
0
async def api_create_blogs(request, *, name, summary, content):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name should not be empty')
    if not summary or not summary.strip():
        raise APIValueError('summary', 'summary should not be empty')
    if not content or not content.strip():
        raise APIValueError('content', 'content should not be empty')
    blog = Blog(user_id=request.__user__.id,
                user_name=request.__user__.name,
                user_image=request.__user__.image,
                summary=summary.strip(),
                name=name.strip(),
                content=content.strip())
    await blog.save()
    return blog
Beispiel #23
0
def addblog():
    if request.method=='POST':
        error=''  
        owner=User.query.filter_by(username=session['username']).first()        
        name = request.form['name']
        content = request.form['content']
        if not name or not content:
            error='     -------Please fill the the name and the content of the blog'
            return render_template('addblog.html',error=error)
        new_blog = Blog(name, content, owner)
        db.session.add(new_blog)
        db.session.commit()
        user_blogs=Blog.query.filter_by(owner_id=new_blog.owner_id).all()
        username=User.query.filter_by(id=new_blog.owner_id).first()
        return render_template('blog.html', user_blogs=user_blogs, username=username)
        
    return render_template('addblog.html')
Beispiel #24
0
def populate():

    for i in range(len(fake_blogs)):
        pop = Blog(
            bid=fake_blogs[i][0],
            title=fake_blogs[i][1],
            sub_title=fake_blogs[i][2],
            author=fake_blogs[i][3],
            date_time=fake_blogs[i][4],
            category=fake_blogs[i][5],
            content=fake_blogs[i][6],
            hidden=False,
            updated=True,
        )
        session.add(pop)
        session.commit()
        print("Fake Blog #" + str(i) + " added!")
Beispiel #25
0
def add_blog():
    data = request.get_json()
    title = data['title']
    content = data['content']
    categories = "-".join(data['categories'])
    name = data['author']
    author = Author.query.filter(Author.user_name == name).first()
    authorId = author.id
    id = myutils.createRandomString(10)
    try:
        blog = Blog(id=id,authorId=authorId,content=content,category=categories,title=title,author=author)
        db.session.add(blog)
        db.session.commit()
        return jsonify({"status":"200","msg":"哈哈,添加博客成功啦~"})
    except:
        db.session.rollback()
        return jsonify({"status":"400","msg":"哎呀,添加博客异常,请您确保输入的信息无误~"}) #返回一个json格式的数据
Beispiel #26
0
async def api_create_blog(request, *, name, summary, content, cat_name):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name cannot be empty.')
    if not summary or not summary.strip():
        raise APIValueError('summary', 'summary cannot be empty.')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty.')
    if not cat_name or not cat_name.strip():
        cat_id = None
    else:
        cats = await Category.find_all(where='name=?', args=[cat_name.strip()])
        cat_id = cats[0].id
 
    blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(), cat_id=cat_id, cat_name=cat_name.strip())
    await blog.save()
    return blog
Beispiel #27
0
def create_blog(channel_name, posted_by, date_posted, title, content, views,
                hearts, date_updated):

    blog = Blog(channel_name=channel_name,
                posted_by=posted_by,
                date_posted=date_posted,
                title=title,
                content=content,
                views=views,
                hearts=hearts,
                date_updated=date_updated)

    db.session.add(blog)

    db.session.commit()

    return blog
Beispiel #28
0
def addpost():
    if request.method == "GET":
        return render_template('newpost.html', title="Add a Blog Entry")

    if request.method == 'POST':
        blog_title = request.form['title']
        blog_body = request.form['body']
        blog_pubdate = datetime.now()
        owner = User.query.filter_by(username=session['username']).first().id
        if len(blog_title)>0 and len(blog_body)>0:
            new_blog = Blog(blog_title, blog_body, blog_pubdate, owner)
            db.session.add(new_blog)
            db.session.commit() 
            return render_template('singlepost.html', blog=new_blog)
        else:
            flash('Blog title or body is empty')
            redirect('/newpost')
Beispiel #29
0
def create_all_blogs():
    db.session.query(Blog).delete()

    sample_articles = [{
        "title": "What is a Stock",
        "url":
        "https://learn.robinhood.com/articles/6FKal8yK9kk22uk65x3Jno/what-is-a-stock/",
        "img": "/static/img/stock-robin.svg"
    }, {
        "title": "What is a portfolio",
        "url":
        "https://learn.robinhood.com/articles/4vaR9PkTzes8u3ibLAWrD1/what-is-a-portfolio/",
        "img": "/static/img/portfolio-robin.svg"
    }, {
        "title": "What is an Initial Public Offering",
        "url":
        "https://learn.robinhood.com/articles/6UsdUrlnUvxiDpDT4D2bup/what-is-an-initial-public-offering-ipo/",
        "img": "/static/img/ipo-robin.svg"
    }, {
        "title": "What is Venture Capital",
        "url":
        "https://learn.robinhood.com/articles/4XRFKEfckD73crXUgLBsoK/what-is-venture-capital/",
        "img": "/static/img/vc-robin.svg"
    }, {
        "title": "What is an Investment Company",
        "url":
        "https://learn.robinhood.com/articles/2FxgvV1Nt0LoTq59xJzj3/what-is-an-investment-company/",
        "img": "/static/img/ic-robin.svg"
    }, {
        "title": "What is a Stock Option",
        "url":
        "https://learn.robinhood.com/articles/YtqceruIQSiHncrlcecPL/what-is-a-stock-option/",
        "img": "/static/img/option-robin.svg"
    }]

    articles_in_db = []
    for article in sample_articles:
        title = article['title']
        url = article['url']
        img = article['img']

        article = Blog(title=title, url=url, img=img)
        articles_in_db.append(article)
        db.session.add(article)
        db.session.commit()
Beispiel #30
0
def publish():
    try:
        title = request.form['title']
        subtitle = request.form['subtitle']
        description = request.form['description']
        content = request.form['content']
        now = int(time.time())
        session = DBSession()
        new_blog = Blog(title=title,
                        description=description,
                        subtitle=subtitle,
                        content=content,
                        time=now)
        session.add(new_blog)
        session.commit()
        session.close()
    except Exception, e:
        app.logger.error(e)