Exemplo n.º 1
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        #db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        #elif db.execute(
        #    'SELECT id FROM user WHERE username = ?', (username,)
        #).fetchone() is not None:
        elif User.query.filter(User.name == username).first() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            #db.execute(
            #    'INSERT INTO user (username, password) VALUES (?, ?)',
            #    (username, generate_password_hash(password))
            #)
            #db.commit()
            u = User(username, password)
            db_session.add(u)
            db_session.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Exemplo n.º 2
0
def register():
    """Register a new user.

    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif User.query.filter(User.username == username).first() is not None:
            error = 'User {0} is already registered.'.format(username)

        if error is None:
            # the name is available, store it in the database and go to
            # the login page
            u = User(username, generate_password_hash(password))
            db_session.add(u)
            db_session.commit()
            return redirect(url_for('auth.login'))
        flash(error)
    return render_template('auth/register.html')
Exemplo n.º 3
0
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            # mysql
            post = Post(title, body, g.user.id)
            db_session.add(post)
            db_session.commit()

            # sqlite3
            # db = get_db()
            # db.execute(
            #     'INSERT INTO post (title, body, author_id)'
            #     ' VALUES (?, ?, ?)',
            #     (title, body, g.user['id'])
            # )
            # db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/create.html')
Exemplo n.º 4
0
def add_entry():
    if not session.get('logged_in'):
        abort(401)
        entry = Entry(request.form['title'], request.form['text'], request.form['pw'])
        db_session.add(entry)
        db_session.commit()
        flash('New entry was successfully posted')
        return redirect(url_for('show_list'))
Exemplo n.º 5
0
 def add_user(cls, password, username, email):
     """Add user to the database"""
     hashed_password = generate_password_hash(password, method='sha256')
     new_user = User(username=username,
                     email=email,
                     password=hashed_password)
     db_session.add(new_user)
     db_session.commit()
Exemplo n.º 6
0
def new():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        u = User()
        u.firstName = request.form['firstName']
        u.lastName = request.form['lastName']
        u.email = request.form['email']
        db_session.add(u)
        db_session.commit()
        flash('New user created.')
        return redirect(url_for('index'))
    else:
        return render_template('new.html', form=form)
Exemplo n.º 7
0
def signup():
    form = RegisterForm()

    if form.validate_on_submit():
        print('test')
        hashed_password = generate_password_hash(
            form.password.data, method='sha256')
        new_user = User(username=form.username.data,
                        email=form.email.data, password=hashed_password)
        db_session.add(new_user)
        db_session.commit()

        return redirect(url_for('login', error="Signup successfully"))
    return render_template('signup.html', form=form)
Exemplo n.º 8
0
def insert_project_info(project_id, json_data, project_info):
    project_info.project_id = project_id  # 查询出来

    project_info.total_quantity = json_data['total_quantity']  # 数据总量
    project_info.crawler_quantity = json_data['crawler_quantity']  # 抓取总量
    project_info.result_quantity = json_data['result_quantity']  # 入库总量

    project_info.crawler_start_time = datetime.datetime.now()  # 开始抓取时间
    project_info.crawler_end_time = datetime.datetime.now()  # 结束时间

    project_info.author = json_data['author']  # 作者
    project_info.partner = json_data['partner']  # 协助者

    db_session.add(project_info)
    db_session.commit()
Exemplo n.º 9
0
def upload():
    """Upload a document."""
    if request.method == 'POST' and 'doc' in request.files:
        try:
            filename = docs.save(request.files['doc'])
            filename = secure_filename(filename)
            print(filename)
            url = docs.url(filename)
            user = User.query.filter_by(id=current_user.id).first()
            user.file_name = filename
            user.file_url = url
            db_session.add(user)
            db_session.commit()
            flash("Doc saved.", "success")
        except UploadNotAllowed:
            flash("The format is not correct.", "danger")
    return render_template('upload.html')
Exemplo n.º 10
0
def add_opinion(tweet_id, flag, opinion_value):
    """Add user's opinion to rumor."""
    print("tweet_id", tweet_id)
    print("opinion", opinion_value)
    print("user_id", current_user.id)
    rumor = Rumor.query.filter_by(tweet_id=tweet_id).first()
    rumor_id = rumor.id
    # check if the record existance
    existed = db_session.query(exists().where(and_(
        Opinion.flag == flag,
        Opinion.stance == opinion_value,
        Opinion.rumor_id == rumor_id,
        Opinion.user_name == current_user.username
    ))).scalar()
    if existed:
        # record existed
        print("record existed")
        print("Opinion", Opinion.query.all())
        r = make_response('existed', 200)
        return r
    else:
        # check if record updation
        print("checking update")
        q = db_session.query(Opinion).filter(and_(
            Opinion.flag == flag,
            Opinion.rumor_id == rumor_id,
            Opinion.user_name == current_user.username
        ))
        if q.all():
            # update record
            print("updating record...")
            q.update({"stance": opinion_value})
            db_session.commit()
            r = make_response('updated', 200)
            return r
    # insert new record
    print("insert record...")
    opinion = Opinion(flag=flag, stance=opinion_value)
    opinion.rumor = rumor
    current_user.rumors.append(opinion)
    db_session.add(current_user)
    db_session.commit()
    print("Opinion", Opinion.query.all())
    r = make_response('inserted', 200)
    return r
Exemplo n.º 11
0
def register():
    """ user register """
    # 1. check username and password
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        # check if username is empty
        if not username:
            error = 'Username is required!'
        # check if password is empty
        elif not password:
            error = 'Password is required!'
        # check if username exists in database
        # mysql 数据库
        elif User.query.filter(User.username == username).first() is not None:
            error = f'User {username} is registered!'
        # sqllite3 数据库
        # elif db.execute(
        #         'SELECT id FROM user WHERE username = ?', (username, )
        #     ).fetchone() is not None:
        #     error = f'User {username} is registered!'

        # everthing is allright, reigster user into database
        if error is None:
            db_session.add(User(username, generate_password_hash(password)))
            db_session.commit()

            # db.execute(
            #     'INSERT INTO user (username, password) VALUES (?, ?)',
            #     (username, generate_password_hash(password))
            # )
            # db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Exemplo n.º 12
0
def insert_project():
    """
    插入一条数据
    {
        "project_name": "ad",
        "total_quantity" : 1,
        "crawler_quantity":1,
        "result_quantity":1,
        "crawler_start_time":1,
        "crawler_end_time":1,
        "author":"小武神",
        "partner":"锦鲤"
    }
    :return:
    """
    json_data = request.get_json()
    project = db_session.query(MonitorProject).filter(
        MonitorProject.project_name == json_data['project_name']).first()
    print("project={}".format(project))

    if not project:
        # 数据库不存在project id
        m = MonitorProject()
        m.project_name = json_data['project_name']
        db_session.add(m)
        db_session.flush()
        db_session.commit()

        project_info = MonitorProjectInfo()
        insert_project_info(m.id, json_data, project_info)
        print(json_data)
    else:
        # 已经存在,跟新其他信息
        project_info = MonitorProjectInfo()
        insert_project_info(project.id, json_data, project_info)
        print(project.id)

    return jsonify({'success': 'true'})
Exemplo n.º 13
0
def add_comment():
    comments = Comment(request.args['id'], request.form['author'], request.form['comment'], request.form['addCommentPassword'])
    db_session.add(comments)
    db_session.commit()
    flash('New comment was successfully posted')
    return redirect(url_for('show_entry', id=request.args['id']))
Exemplo n.º 14
0
    def add_data(self, eventName):
        """Initialize the data in the database."""
        # load events
        print("adding {} data...".format(eventName))

        eventPath = self.dataRootPath / eventName

        terms = [
            term for term in eventPath.name.split('_') if not term.isdigit()
        ]
        edited_event = " ".join(terms)
        tableEvent = CreateDatabaseTable.create_event(edited_event)

        origin_statement_id = edited_event + "_" + "origin_statement"
        origin_statement = Helper.getEventClaims(eventPath)
        tableOriginStatement = CreateDatabaseTable.create_origin_statement(
            origin_statement_id, origin_statement)
        tableEvent.origin_statement = tableOriginStatement

        clustersPath = eventPath / 'clusterData'
        clusters = [
            cluster for cluster in clustersPath.iterdir() if cluster.is_dir()
        ]
        for cluster in clusters:
            clusterTable = CreateDatabaseTable.create_cluster(cluster)
            tableEvent.clusters.append(clusterTable)
            event_cluster_id = edited_event + "_" + cluster.name
            # tableEvent_Cluster = CreateDatabaseTable.combine_event_cluster(
            # event_cluster_id, tableEvent, clusterTable)
            # get statements
            statementClusters = [
                statementCluster
                for statementCluster in (cluster / "classification").iterdir()
                if statementCluster.is_dir()
            ]
            for statementCluster in statementClusters:
                # load data
                statement = Helper.getRepresentativeClaim(statementCluster)
                rumors = Helper.getClusterClaims(statementCluster)
                # snippets = Helper.getNews(cluster, statementCluster.name)
                snippets = Helper.getSnippets(statementCluster)
                # check all data
                if not (statement and rumors and snippets):
                    continue

                print("successfully load cluster data ", statementCluster)
                # print("statement ", statement)
                statement_id = event_cluster_id + "_" + statementCluster.name
                tableStatement = CreateDatabaseTable.create_statement(
                    statement_id, statement)
                if not tableStatement:
                    continue
                # continue
                # tableRumor = CreateDatabaseTable.create_rumor(rumor, rumor_id)
                # tableEvent_Cluster.rumors.append(tableRumor)

                # get rumors

                for indexRumor, rumor in enumerate(rumors):
                    rumor_id = statement_id + "_" + str(indexRumor)
                    tableRumor = CreateDatabaseTable.create_rumor(
                        rumor, rumor_id)
                    if not tableRumor:
                        continue
                    # tableEvent_Cluster.rumors.append(tableRumor)
                    tableStatement.rumors.append(tableRumor)

                # # news
                # for indexSnippet, snippet in enumerate(snippets):
                #     snippet_id = statement_id + "_" + str(indexSnippet)
                #     tableSnippet = CreateDatabaseTable.create_snippet(
                #         snippet_id, snippet)
                #     if not tableSnippet:
                #         continue
                #     tableStatement.snippets.append(tableSnippet)

                # snippets
                for indexSnippet, snippet in enumerate(snippets):
                    snippet_id = statement_id + "_" + str(indexSnippet)
                    tableSnippet = CreateDatabaseTable.create_snippet(
                        snippet_id, snippet)
                    if not tableSnippet:
                        continue
                    tableStatement.snippets.append(tableSnippet)

                # tableEvent_Cluster.statements.append(tableStatement)
                tableEvent.cluster_associations[-1].statements.append(
                    tableStatement)
                db_session.add(clusterTable)
                # print("commit")
                db_session.commit()