예제 #1
0
def get_article(article_id):
    article = Article().query.filter_by(article_id=article_id).first()
    article.article_read_cnt = article.article_read_cnt + 1
    db.session.add(article)
    db.session.commit()
    articles = Article().query.limit(8)
    return render_template('article.html', article=article, articles=articles)
예제 #2
0
def teste_2():
    from app.models import Publication, Article

    p1 = Publication(title='The Python Journal')
    p1.save()
    p2 = Publication(title='Science News')
    p2.save()
    p3 = Publication(title='Science Weekly')
    p3.save()

    a1 = Article(headline='Django lets you build Web apps easily')

    # a1.publications.add(p1) #You can’t associate it with a Publication until it’s been saved:
    a1.save()
    a1.publications.add(p1)

    a2 = Article(headline='NASA uses Python')
    a2.save()
    a2.publications.add(p1, p2)

    print()

    print()

    print()

    print()

    print()

    print()

    print()
예제 #3
0
def article_add():

    art = Article(title="这是一个标题2", content="这是文章内容2")
    art2 = Article(title="这是标题3", content="这是内容3")
    # 将数据保存到数据库中
    db.session.add(art)
    db.session.add(art2)
    db.session.commit()
    return '返回值:%s' % art.id
예제 #4
0
def get_others():
    articles = Article().query.filter_by(article_type='其他').all()
    page = request.args.get('page', 1, type=int)

    pagination = Article().query.filter_by(article_type='java').paginate(
        page, per_page=3, error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           articles=articles,
                           posts=posts,
                           pagination=pagination)
예제 #5
0
def index():
    articles = Article().query.all()
    print(articles)
    page = request.args.get('page', 1, type=int)
    pagination = Article().query.paginate(page, per_page=3, error_out=False)
    posts = pagination.items
    print(posts)
    return render_template('main/index.html',
                           articles=articles,
                           posts=posts,
                           pagination=pagination)
def reconcile_articles():
    producer = ArticleProducer()
    repo_name = 'temp_repo'
    print("Cloning articles repository...")
    shutil.rmtree(repo_name, ignore_errors=True)
    repo = Repo.clone_from(ARTICLES_REPO, repo_name)
    with os.scandir(repo_name) as entries:
        for entry in entries:
            if entry.is_file():
                existing_article = col.find_one({'_id': entry.name})
                last_modified = repo.git.log('-1', entry.name, format='%aI')
                lm_date = datetime.fromisoformat(last_modified)
                if (existing_article != None and (datetime.fromisoformat(
                        existing_article['last_modified_date']) == lm_date)):
                    "Skip files which have not changed"
                    continue
                created = repo.git.log(entry.name,
                                       format='%aI',
                                       diff_filter='A').split('\n')[-1]
                created_date = datetime.fromisoformat(created)
                with open(entry, 'r') as f:
                    data = f.read()
                    soup = BeautifulSoup(data, 'html.parser')
                    print('Publishing article key: ' + entry.name)
                    article = Article({
                        'title':
                        soup.find_all('article-title')[0].string,
                        'filename':
                        entry.name,
                        'html':
                        data,
                        'created_date':
                        created_date.astimezone(tz=timezone.utc).isoformat(),
                        'last_modified_date':
                        lm_date.astimezone(tz=timezone.utc).isoformat(),
                        'deleted':
                        False
                    })
                    producer.send(article)
    "Mark non-existant articles for deletion"
    for article in col.find({}, {'_id': 0}):
        article_c = Article(article)
        if not os.path.exists(os.path.join(repo_name, article_c.filename)):
            article_c.deleted = True
            producer.send(article_c)

    print("Cleaning up temporary files...")
    shutil.rmtree(repo_name)
    return "success"
예제 #7
0
파일: rest.py 프로젝트: NewAcropolis/api
def import_articles():
    data = request.get_json(force=True)

    validate(data, post_import_articles_schema)

    articles = []
    errors = []
    for item in data:
        err = ''
        article = Article.query.filter(Article.old_id == item['id']).first()
        if not article:
            article = Article(
                old_id=item['id'],
                title=item['title'],
                author=item['author'],
                content=item['content'],
                created_at=item['entrydate'] if item['entrydate'] != '0000-00-00' else None,
                image_filename=item['image_filename'] if 'image_filename' in item else None
            )

            articles.append(article)
            dao_create_article(article)
        else:
            err = u'article already exists: {} - {}'.format(article.old_id, article.title)
            current_app.logger.info(err)
            errors.append(err)

    res = {
        "articles": [a.serialize() for a in articles]
    }

    if errors:
        res['errors'] = errors

    return jsonify(res), 201 if articles else 400 if errors else 200
예제 #8
0
 def setup(self):
     '''
     Set up method that will run before every Test
     '''
     self.new_article = Article("20 more people dead",
                                "It was a long car accident", "null", 10,
                                "A lot of things", 'http//bbc')
예제 #9
0
파일: commands.py 프로젝트: 2017212212183/-
def forge():
    """Generate fake data."""
    db.create_all()
    # 用户表
    for m in users:
        user = User(email=m['email'],
                    password=m['password'],
                    head=m['head'],
                    isAdmin=m['isAdmin'],
                    description=m['description'],
                    time=datetime.now())
        db.session.add(user)
    # 文章表
    for m in articles:
        article = Article(articleId=m['articleId'],
                          title=m['title'],
                          Author=m['Author'],
                          type_id=m['type_id'],
                          text=m['text'],
                          image=m['image'],
                          modified_date=datetime.now(),
                          thumbsUp=m['thumbsUp'],
                          eyeOpen=m['eyeOpen'])
        db.session.add(article)
    db.session.commit()
    click.echo('Done.')
예제 #10
0
def add_article(current_user):
    try:
        data = request.form
        files = request.files
        article = Article()
        article.title = data['title']
        article.category = data['category']
        article.author = data['author']
        article.author_desc = data['author_desc']
        article.date = datetime.strptime(str(data['date']),'%Y-%m-%d')
        article.image = files['image'].read()
        article.caption = data['caption']
        article.text = data['text']
        if 'chart1' in files:
            article.chart1 = files['chart1'].read()
        article.chart1_caption = data.get('chart1','')
        if 'chart2' in files:
            article.chart2 = files['chart2'].read()
        article.chart2_caption = data.get('chart2','')
        db.session.add(article)
        db.session.commit()
        return jsonify({
            'status': 'SUCCESS',
            'data': {},
        })
    except Exception as e:
        print(e)
        return jsonify({
            'status': 'ERROR',
            'data': str(e),
        })
예제 #11
0
def article_create():
    if request.method == "GET":
        return render_template('article/create.html')
    elif request.method == "POST":
        title = request.form.get('title')
        content = request.form.get('content')
        article_id = request.form.get('article_id')

        new_article = Article(title=str(title), content=str(content))

        try:
            if article_id:
                article = Article.query.filter_by(id=article_id).first()
                article.title = title
                article.content = content

            else:
                db.session.add(new_article)
            db.session.commit()

        except:
            db.session.rollback()

        finally:
            return redirect(url_for('main.article_index'))
예제 #12
0
파일: admin.py 프로젝트: Lemon000/Blog
def all_article():
    page = request.args.get('page', 1, type=int)
    pagination = Article().query.paginate(page, per_page=10, error_out=False)
    articles = pagination.items
    return render_template('admin/all_article.html',
                           articles=articles,
                           pagination=pagination)
예제 #13
0
    def test_article_one_compound_model(self):
        # Create compound
        cmpd = Compound(name='Methane',
                        smiles='C',
                        source_organism='Saccharomyces cerevisiae')
        # Create article with compound
        art = Article(pmid=12345,
                      journal='Test Journal',
                      year=2018,
                      volume='12',
                      issue='12',
                      pages='1-1000',
                      authors='Douglas Adams',
                      doi='10.1234/HHGTTG',
                      title='HHGTTG',
                      abstract='Test Abstract',
                      num_compounds=1,
                      compounds=[cmpd])
        db.session.add(art)
        db.session.commit()

        # Tests
        self.assertEqual(Article.query.count(), 1)
        self.assertEqual(len(Article.query.first().compounds), 1)
        self.assertEqual(Article.query.first().compounds[0].id, 1)
예제 #14
0
    def test_one_article_one_compound_dataset_model(self):
        # Create compound
        cmpd = Compound(name='Methane',
                        smiles='C',
                        source_organism='Saccharomyces cerevisiae')
        # Create article with compound
        art = Article(pmid=12345,
                      journal='Test Journal',
                      year=2018,
                      volume='12',
                      issue='12',
                      pages='1-1000',
                      authors='Douglas Adams',
                      doi='10.1234/HHGTTG',
                      title='HHGTTG',
                      abstract='Test Abstract',
                      num_compounds=1,
                      compounds=[cmpd])

        # Get curator
        curator = Curator.query.filter_by(username='******').first()
        self.assertEqual(curator.username, 'test_user')

        # Create empty dataset and add
        ds = Dataset(curator=curator, articles=[art])
        db.session.add(ds)
        db.session.commit()

        # Tests
        self.assertEqual(Dataset.query.count(), 1)
        self.assertEqual(len(Dataset.query.first().articles), 1)
        self.assertEqual(Dataset.query.first().articles[0].pmid, 12345)
        self.assertEqual(len(Dataset.query.first().articles[0].compounds), 1)
        self.assertEqual(Dataset.query.first().articles[0].compounds[0].name,
                         'Methane')
예제 #15
0
    def test_one_article_no_compounds_dataset_model(self):
        # Create article without compound
        art = Article(pmid=12345,
                      journal='Test Journal',
                      year=2018,
                      volume='12',
                      issue='12',
                      pages='1-1000',
                      authors='Douglas Adams',
                      doi='10.1234/HHGTTG',
                      title='HHGTTG',
                      abstract='Test Abstract',
                      num_compounds=0)

        # Get curator
        curator = Curator.query.filter_by(username='******').first()
        self.assertEqual(curator.username, 'test_user')

        # Create empty dataset and add
        ds = Dataset(curator=curator, articles=[art])
        db.session.add(ds)
        db.session.commit()

        # Tests
        self.assertEqual(Dataset.query.count(), 1)
        self.assertEqual(Dataset.query.first().curator.username, 'test_user')
        self.assertEqual(len(Dataset.query.first().articles), 1)
        self.assertEqual(Dataset.query.first().articles[0].pmid, 12345)
예제 #16
0
 def setUp(self):
     '''Instantiate article class'''
     self.objArticle = Article(
         'cnn.com', 'Mr Mike', 'Example Article Title',
         'This is an article description', 'http://cnn.com',
         'http://cnn.com', '2012-05-03',
         'This article content, read and be informed')
예제 #17
0
    def test_str(self):
        article = Article()
        article.entry_number = '7399422'
        article.author = 'R. Atia and N. Yamada'
        article.journal = 'IEEE Transactions on Smart Grid'
        article.title = 'Sizing and Analysis of Renewable Energy and Battery Systems in Residential Microgrids'
        article.year = '2016'
        article.volume = '7'
        article.number = '3'
        article.pages = '1204-1213'
        article.abstract = 'Accelerated development of eco-friendly technologies such as renewable energy smart grids and electric transportation will shape the future of electric power generation and supply. Accordingly the power consumption characteristics of modern power systems are designed to be more flexible which impact the system sizing. However integrating these considerations into the design stage can be complex. Under these terms this paper presents a novel model based on mixed integer linear programming for the optimization of a hybrid renewable energy system with a battery energy storage system in residential microgrids in which the demand response of available controllable appliances is coherently considered in the proposed optimization problem with reduced calculation burdens. The model takes into account the intrinsic stochastic behavior of renewable energy and the uncertainty involving electric load prediction and thus proper stochastic models are considered. This paper investigates the effect of load flexibility on the component sizing of the system for a residential microgrid in Okinawa. Also under consideration are different operation scenarios emulating technical limitations and several uncertainty levels.'
        article.keyword = 'battery storage plants;demand side management;distributed power generation;hybrid power systems;integer programming;linear programming;load forecasting;renewable energy sources;smart power grids;Okinawa;battery energy storage system;battery systems;demand response;eco-friendly technologies;electric load prediction;electric power generation;electric transportation;hybrid renewable energy system;load flexibility;mixed integer linear programming;power systems;residential microgrids;smart grids;Batteries;Home appliances;Load modeling;Microgrids;Optimization;Renewable energy sources;Stochastic processes;Design optimization;demand response;hybrid power systems;microgrids;performance analysis'
        article.doi = '10.1109/TSG.2016.2519541'
        article.issn = '1949-3053'

        benchmark = '@article{7399422,\n' \
                    ' abstract = {Accelerated development of eco-friendly technologies such as renewable energy smart grids and electric transportation will shape the future of electric power generation and supply. Accordingly the power consumption characteristics of modern power systems are designed to be more flexible which impact the system sizing. However integrating these considerations into the design stage can be complex. Under these terms this paper presents a novel model based on mixed integer linear programming for the optimization of a hybrid renewable energy system with a battery energy storage system in residential microgrids in which the demand response of available controllable appliances is coherently considered in the proposed optimization problem with reduced calculation burdens. The model takes into account the intrinsic stochastic behavior of renewable energy and the uncertainty involving electric load prediction and thus proper stochastic models are considered. This paper investigates the effect of load flexibility on the component sizing of the system for a residential microgrid in Okinawa. Also under consideration are different operation scenarios emulating technical limitations and several uncertainty levels.},\n' \
                    ' author = {R. Atia and N. Yamada},\n' \
                    ' doi = {10.1109/TSG.2016.2519541},\n' \
                    ' issn = {1949-3053},\n' \
                    ' journal = {IEEE Transactions on Smart Grid},\n' \
                    ' keyword = {battery storage plants;demand side management;distributed power generation;hybrid power systems;integer programming;linear programming;load forecasting;renewable energy sources;smart power grids;Okinawa;battery energy storage system;battery systems;demand response;eco-friendly technologies;electric load prediction;electric power generation;electric transportation;hybrid renewable energy system;load flexibility;mixed integer linear programming;power systems;residential microgrids;smart grids;Batteries;Home appliances;Load modeling;Microgrids;Optimization;Renewable energy sources;Stochastic processes;Design optimization;demand response;hybrid power systems;microgrids;performance analysis},\n' \
                    ' number = {3},\n' \
                    ' pages = {1204-1213},\n' \
                    ' title = {Sizing and Analysis of Renewable Energy and Battery Systems in Residential Microgrids},\n' \
                    ' volume = {7},\n' \
                    ' year = {2016}\n' \
                    '}\n\n'

        self.assertEqual(str(article), benchmark)
예제 #18
0
def del_article(article_id):
    print('article_id=', article_id)
    article = Article().query.filter_by(article_id=article_id).first()
    db.session.delete(article)
    db.session.commit()
    print('删除文章成功!!!!')
    return redirect(url_for('main.manage_article'))
예제 #19
0
 def setUp(self):
     '''method that will run before each test case'''
     self.new_article = Article(
         '123', "Title of the article", 'description of the article',
         'https://abcnews.go.com/theview/video/andrea-kelly-details-allegations-abuse-husband-kelly-58286731',
         'https://s.abcnews.com/images/theview/181004_view_andrea_1134_hpMain_16x9_992.jpg',
         '2018-10-04T18:14:14Z', 'content of the article')
예제 #20
0
def article_upload():
    img = request.files['imgfile']
    img_filename = change_filename(img.filename)  # 更改图片名称
    save_url = app.config["UP_DIR"] + "upload/" + img_filename  # 图片保存地址
    img.save(save_url)  # 保存图片
    zoom(save_url, save_url)  # 压缩图片
    data = request.form.to_dict()
    user = User.query.filter_by(uuid=data['userid']).first()
    dic = {}
    if int(data['isPose']) == 1:  # 判断是否需要姿势点
        dic = pose.pose(
            save_url,
            app.config["UP_DIR"] + "upload/" + "posture" + img_filename)
    article = Article(
        title=data["title"],
        content=data["content"],
        spotid=data["spotid"],
        img="http://www.yujl.top:5052/upload/" + img_filename,
        postpoint=str(dic),
        weather=data["weather"],
        userid=user.id,
        good=0,
        time=datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
        keyword=data["keyword"],
        poseimg="http://www.yujl.top:5052/upload/" + "posture" + img_filename)
    db.session.add(article)
    db.session.commit()

    return jsonify({"code": 1})
예제 #21
0
def edit_article(article_id):
    article = Article().query.filter_by(article_id=article_id).first()
    if request.method == 'POST':
        article_title = request.form.get('article_title')
        artitle_type = request.form.get('f_type')
        article_text = request.form.get('article_content')
        article_url = request.form.get('article_url')
        article_text = markdown.markdown(article_text, ['extra', 'codehilite'])
        # article_date = strftime('%Y-%m-%d %H:%M:%S')
        article_date = datetime.utcnow()
        if artitle_type == '1':
            article_type = 'python'
        elif artitle_type == '2':
            article_type = 'java'
        else:
            article_type = '其他'
        content = re.compile('.*?>(.*?)<').findall(article_text)
        article_summary = ''
        for x in content:
            if x:
                article_summary = article_summary + x
                if len(article_summary) > 250:
                    break
        article_summary = "".join(article_summary.split())
        article.article_title = article_title
        article.article_type = article_type
        article.article_text = article_text
        article.article_summary = article_summary[:180]
        article.article_url = article_url
        db.session.add(article)
        db.session.commit()
        return redirect(url_for('main.get_article', article_id=article_id))
    return render_template('article/wrarticle.html', article=article)
예제 #22
0
 def setUp(self):
     """
     set up  method will run before every Test
     """
     self.new_article = Article("title", "name", "description",
                                "www.test.com", "test.com/img",
                                "2018-05-13T06:36:21Z", "Sarah")
예제 #23
0
def del_article(article_id):
    article = Article().query.filter_by(article_id=article_id).first()
    db.session.delete(article)
    comments = Comment().query.filter_by(article_id=article_id).delete(
        synchronize_session=False)
    db.session.commit()
    return redirect(url_for('main.manage_article'))
예제 #24
0
파일: views.py 프로젝트: CoderGrowing/Blog
def write_article():
    if current_user.role != "Admin":
        flash(u'您没有权限访问该页面!')
        return redirect(url_for('main.index'))
    if request.method == 'POST':
        article = Article(heading=request.form['heading'], body=request.form['article'],
                          article_type=request.form['article_type'], permission=request.form['permission'],
                          article_len=request.form['word-count']
                          )
        db.session.add(article)

        tags = request.form['tag-name']
        article_tags = []

        for i in tags.split(','):
            article_tags.append(i)

        article_tags = article_tags[:-1]
        for article_tag in article_tags:
            tag = Tag.query.filter_by(name=article_tag).first()
            if not tag:
                tag = Tag(name=article_tag)
                db.session.add(tag)
                article.tags.append(tag)
                db.session.add(article)
            else:
                article.tags.append(tag)
        flash(u'文章提交成功!')

        return redirect(url_for('main.index'))

    return render_template('write-article.html')
예제 #25
0
 def setUp(self):
     '''
     Set up method that will run before every test
     '''
     self.new_article = Article('Test author', 'Test title',
                                'Test description', 'Test url',
                                'Test image', 'Test publishedAt')
예제 #26
0
def post():
    title = "写文章"
    form = PostForm()
    if form.validate_on_submit():
        #basepath = os.path.dirname(__file__)  # 当前文件所在路径
        #fileGet='uploads/assignment{}'.format(HOMEWORK_TIME)
        #upload_path = os.path.join(basepath,fileGet,secure_filename(fpy.filename))
        savepic_path = 'app/static/assets/img/' + form.file.data.filename
        form.file.data.save(savepic_path)
        cate = Category.query.filter_by(name=dict(form.categories.choices).get(
            form.categories.data)).first_or_404()
        cate.number = cate.number + 1
        article = Article(title=form.title.data,
                          body=form.body.data,
                          create_time=datetime.now(),
                          pic_path='static/assets/img/' +
                          form.file.data.filename,
                          category_id=cate.id)
        db.session.add(article)
        db.session.commit()
        flash('上传成功!')
        return redirect(url_for('index'))
    #if request.method=='POST':
    #	fpic=request.files['editormd-image-file']
    #	bodypic_path='app/static/pic/'+fpic.filename
    #	fpic.save(bodypic_path)
    return render_template('/admin/post.html',
                           title=title,
                           form=form,
                           category=category)
예제 #27
0
    def setUp(self):
        '''
        Set up method that will run before every Test
        '''

        self.new_article = Article(
            "bbc-news", "BBC News", "Police search homes in Streatham attack probe", "Two addresses are searched as it emerges attacker Sudesh Amman was released from prison last month.", "http://www.bbc.co.uk/news/uk-51356447", "https://ichef.bbci.co.uk/news/1024/branded_news/D862/production/_104849355_terror105-18amman.jpg", "2020-02-03T09:43:01Z", "Image copyrightMet Police Police have been searching two addresses as part of the investigation into the attack in Streatham on Sunday")
예제 #28
0
def create_article():
    """ Create article page """
    if current_user.role < ACCESS['admin']:
        return "<h1>Доступ заборонений.</h1>"
    if request.method == "POST":
        title = request.form.get("title")
        post_info = request.form.get("text")
        uploaded_file = request.files['thumbnail']
        filename = secure_filename(uploaded_file.filename)
        file_id = datetime.now().strftime("%Y%m%H%M%S%f")

        if filename == '':
            flash("Ви не вибрали зображення", "error")
            return render_template('posts/create-post.html',
                                   title_value=title,
                                   text_value=post_info)

        uploaded_file.save(
            os.path.join(app.config['THUMBNAILS_FOLDER'], file_id))
        new_post = Article(title=title,
                           text=post_info,
                           user_id=current_user.id,
                           thumbnail=file_id)
        db.session.add(new_post)
        db.session.commit()
        flash("Стаття була успішно створена", "info")
    return render_template('posts/create-post.html')
예제 #29
0
def create_article(data, board_Name):
    if 'session' in web_session:
        user_id = redisSession.open_session(web_session['session'])
        if user_id:
            article = Article(
                board = session.query(Board).filter_by(name=board_Name).first().id,
                writer = user_id,
                title = data['title'],
                content = data['content']
            )
            save(article)
            response = {
                'status': 'success',
                'message': 'Create article successfully'
            }
            return response, 201
        else:
            response = {
                'status': 'fail',
                'message': 'Permission denied'
            }
            return response, 401
    else:
        response = {
            'status': 'fail',
            'message': 'Login required'
        }
        return response, 403
예제 #30
0
 def setup(self):
     """
     Set up method that will run before every Test
     """
     self.new_article = Article("bloomberg", "TestTitle", "TestDescription",
                                "TestUrl", "TestUrlToImage",
                                "TestPublishedAt", "TestContent")