Exemple #1
0
def fake_tags(count=10):
    tag = Tags(name='Default')
    db.session.add(tag)

    for i in range(count):
        tag = Tags(name=fake.word())
        db.session.add(tag)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
Exemple #2
0
def write():
    if request.method == 'GET':
        return render_template('home/myblog/add.html')
    elif request.method == 'POST':
        try:
            # 添加文章
            a = Article()
            a.title = request.form['title']
            a.context = request.form['content']
            a.type_id = request.form['pid']
            a.uid = session['VipUser']['uid']
            db.session.add(a)
            db.session.commit()
        except:
            db.session.rollback()
            return '文章添加失败'

        try:
            # 添加标签
            ts = request.form['tags'].split(',')
            tagsarr = []
            for x in ts:
                # 判断数据库是否存在tags标签
                tags = Tags.query.filter_by(tagname=x, uid=session['VipUser']['uid']).first()
                if tags:
                    # 判断当前标签如果已经存在,则直接获取id
                    tagsarr.append(tags.id)
                else:
                    # 如果不存在,则添加到数据库,获取id
                    t = Tags()
                    t.uid = session['VipUser']['uid']
                    t.tagname = x
                    db.session.add(t)
                    db.session.commit()
                    tagsarr.append(t.id)
        except:
            db.session.rollback()
            return '标签创建失败'

        try:
            # # 搞定 标签和文章关系
            for x in tagsarr:
                at = Ats()
                at.article_id = a.id
                at.tags_id = x
                db.session.add(at)
                db.session.commit()
        except:
            db.session.rollback()
            return '标签和文章关系创建失败'

        uname = session['VipUser']['uname']
        return '<script>alert("文章发布成功");location.href="/' + uname + '/"</script>'
Exemple #3
0
    def generate_tags(self, cnt):
        if cnt is None:
            return False

        print('Generate {} tags'.format(cnt))
        tags = [Tags(title=f.word() + str(i)) for i in range(cnt)]
        self.insert_data(Tags, tags)
Exemple #4
0
def index(city=None):

    city = City.query.filter_by(name=city).first()

    available_citys = City.query.all()
    folder = os.environ.get('ICON_FOLDER')
    filelist = []
    for x in os.listdir(folder):
        filelist.append(x)
    citys_list = [(i.id, i.name) for i in available_citys]

    form_task = TaskForm()

    form_task.city.choices = citys_list

    if form_task.validate_on_submit():
        print('in form')
        city = City.query.get(form_task.city.data)
        print('in form')
        task = Task(body=form_task.body.data,
                    author=current_user,
                    internet=form_task.internet.data,
                    summary=form_task.summary.data,
                    price=form_task.price.data,
                    currency=form_task.currency.data,
                    status='open')

        folder = form_task.folder_name.data

        for x in os.listdir(folder):
            print(x)

        tags = form_task.tags.data
        tags = tags[:-1]
        tags = tags.split('%')

        db.session.add(task)
        db.session.commit()

        for tag in tags:
            tagout = Tags.query.filter_by(name=tag).first()
            if tagout is not None:
                task.tags.append(tagout)
            else:
                tagout = Tags(name=tag)
                task.tags.append(tagout)

        db.session.commit()

        scity = City.query.get(form_task.city.data)
        scity.citytasks.append(task)
        db.session.commit()
        return redirect(url_for('main.index'))

    return render_template('index.html',
                           form_task=form_task,
                           filelist=filelist)
Exemple #5
0
def updateTags(series, tags, deleteother=True, allow_new=True):
    havetags = Tags.query.filter((Tags.series == series.id)).all()
    havetags = {item.tag.lower(): item for item in havetags}

    tags = [tag.lower().strip().replace(" ", "-") for tag in tags]
    tags = [bleach.clean(item, strip=True) for item in tags]
    tags = [tag for tag in tags if tag.strip()]

    # Pipe through the fixer lut
    tags = [tag_lut.tag_fix_lut.get(tag, tag) for tag in tags]

    for tag in [n for n in tags]:
        if tag in tag_lut.tag_extend_lut:
            tags.append(tag_lut.tag_extend_lut[tag])

    tags = set(tags)

    for tag in tags:
        if tag in havetags:
            havetags.pop(tag)
        else:
            # If we're set to allow new, don't bother checking for other instances of the tag.
            if allow_new:
                newtag = Tags(series=series.id,
                              tag=tag,
                              changetime=datetime.datetime.now(),
                              changeuser=getCurrentUserId())
                db.session.add(newtag)
            else:
                # Otherwise, make sure that tag already exists in the database before adding it.
                exists = Tags.query.filter((Tags.tag == tag)).count()
                if exists:
                    newtag = Tags(series=series.id,
                                  tag=tag,
                                  changetime=datetime.datetime.now(),
                                  changeuser=getCurrentUserId())
                    db.session.add(newtag)

    if deleteother:
        for dummy_key, value in havetags.items():
            db.session.delete(value)

    db.session.commit()
def new_list():
    if request.method == "POST":
        e = Entries.query.filter_by(user_id=current_user.id,
                                    text=request.form['entry']).first()
        t = Tags.query.filter_by(tag=request.form['tag']).first()
        if t is None:
            t = Tags(tag=request.form['tag'])
            db.session.add(t)
        if e is None:
            e = Entries(user_id=current_user.id, text=request.form['entry'])
        e.tags.append(t)
        db.session.add(e)
        db.session.commit()
    return render_template('new.html')
def new_entry():
    e = Entries.query.filter_by(user_id=current_user.id,
                                text=request.form['entry']).first()
    t = Tags.query.filter_by(tag=request.form['tag']).first()
    if e is None:
        e = Entries(user_id=current_user.id, text=request.form['entry'])
    if t is None:
        t = Tags(tag=request.form['tag'])
    e.tags.append(t)
    db.session.add(e)
    db.session.commit()
    id = Entries.query.filter_by(user_id=current_user.id,
                                 text=request.form['entry']).first().id
    return str(id)
Exemple #8
0
def movie_add():
    form = MovieForm()

    # 查询数据库标签并赋值给表单,此方法可以实时同步数据库的标签数据
    # 避免新添加的标签无法显示
    form.tag_id.choices = Tags.get_all_tags()
    if request.method == "POST":
        if form.validate_on_submit():
            data = form.data
            # 若已经存在则不再添加
            if Movie.query.filter(
                    or_(Movie.logo == data['logo'], Movie.url == data['url'],
                        Movie.title == data['title'])).all():
                flash("电影已经存在,请不要重复添加", "err")
            else:
                with db.auto_commit():
                    file_url = secure_filename(form.url.data.filename)
                    file_logo = secure_filename(form.logo.data.filename)
                    if not os.path.exists(app.config["UP_DIR"]):
                        os.makedirs(app.config["UP_DIR"])
                        os.chmod(app.config["UP_DIR"], "rw")

                    url = change_filename(file_url)
                    logo = change_filename(file_logo)
                    form.url.data.save(app.config["UP_DIR"] + url)
                    form.logo.data.save(app.config["UP_DIR"] + logo)
                    new_movie = Movie(title=data['title'],
                                      url=url,
                                      logo=logo,
                                      info=data['info'],
                                      star=int(data['star']),
                                      tag_id=int(data['tag_id']),
                                      area=data['area'],
                                      release_time=data['release_time'],
                                      length=data['length'])
                    db.session.add(new_movie)

                    # 记录电影添加操作
                    new_adminlog = OpLog(admin_id=session['id'],
                                         ip=session['login_ip'],
                                         reason="添加电影: 《" + new_movie.title +
                                         "》")
                    db.session.add(new_adminlog)
                flash("电影添加成功", "addok")
                return redirect(url_for("admin.movie_add"))
        else:
            flash("电影添加失败", 'err')
            return redirect(url_for("admin.movie_add"))
    return render_template("admin/movie_add.html", form=form)
Exemple #9
0
    def dbsetup():
        """Seperate function just for the creation of test DB entries"""
        test_tag_1 = Tags(name="test_tag_1")
        test_tag_2 = Tags(name="test_tag_2")
        test_post_1 = Post(name="test post 1",
                           description="",
                           description_body="",
                           image="",
                           post_type="project")
        # First test post is project post

        db.session.add(test_tag_1)
        db.session.add(test_tag_2)
        db.session.add(test_post_1)
        db.session.commit()

        for x in range(2, 10):  # other post are blogposts
            test_pagination_post = Post(name="test post {}".format(x),
                                        description="",
                                        description_body="",
                                        image="",
                                        post_type="blogpost")
            db.session.add(test_pagination_post)
            db.session.commit()
Exemple #10
0
def movie_edit(id=None):
    form = EditMovieForm()
    # 查询数据库标签并赋值给表单,此方法可以实时同步数据库的标签数据
    # 避免新添加的标签无法显示
    form.tag_id.choices = Tags.get_all_tags()

    movie = Movie.query.filter_by(id=id).first()

    if request.method == "POST":
        if form.validate_on_submit():
            data = form.data

            with db.auto_commit():
                file_logo = secure_filename(form.logo.data.filename)
                if not os.path.exists(app.config["UP_DIR"]):
                    os.makedirs(app.config["UP_DIR"])
                    os.chmod(app.config["UP_DIR"], "rw")

                logo = change_filename(file_logo)
                form.logo.data.save(app.config["UP_DIR"] + logo)

                movie.title = data['title'],
                movie.logo = logo,
                movie.info = data['info'],
                movie.star = int(data['star']),
                movie.tag_id = int(data['tag_id']),
                movie.area = data['area'],
                movie.release_time = data['release_time'],
                movie.length = data['length']

                db.session.add(movie)

                # 记录编辑电影操作
                new_adminlog = OpLog(admin_id=session['id'],
                                     ip=session['login_ip'],
                                     reason="编辑电影: 《" + data['title'] + "》")
                db.session.add(new_adminlog)
            flash("电影编辑成功", "ok")
            return redirect(url_for("admin.movie_edit", id=id))
        else:
            flash("电影编辑失败", 'err')
            return redirect(url_for("admin.movie_edit", id=id))

    return render_template("admin/movie_edit.html", form=form)
Exemple #11
0
def tag_add():
    form = TagForm()
    if form.validate_on_submit():
        data = form.data
        # 查询是否已经存在该标签
        if Tags.query.filter_by(name=data['name']).first():
            flash("已经存在该标签!", "err")
        else:
            with db.auto_commit():
                tag = Tags(name=data['name'])
                db.session.add(tag)
                # 记录添加标签操作
                new_adminlog = OpLog(admin_id=session['id'],
                                     ip=session['login_ip'],
                                     reason="添加标签: " + tag.name)
                db.session.add(new_adminlog)
            # flash("标签添加成功!", "ok")
            return redirect(url_for("admin.tag_add"))
    return render_template("admin/tag_add.html", form=form)
Exemple #12
0
def tags():
    if request.method == 'GET':
        # query = "SELECT DISTINCT tag,color FROM tags GROUP BY tag"
        query = "SELECT tag, COUNT(*), color FROM tags GROUP BY tag"
        result = db.session.execute(query)
        return render_template('tags.html', data=result)
    elif request.method == 'POST':
        print(request.form)
        tag = request.form['tag']
        projectID = -1
        color = request.form['color']

        if tag and color:
            db.session.add(Tags(tag=tag, projectID=projectID, color=color))
            db.session.commit()
            db.session.close()
            return json.dumps({'html': '<span>Tag Added</span>'})
        else:
            return json.dumps(
                {'html': '<span>Enter the required fields</span>'})
def index():
    info = request.form
    if request.method == "POST":
        if 'entry' in info:
            e = Entries.query.filter_by(user_id=current_user.id,
                                        text=request.form['entry']).first()
            t = Tags.query.filter_by(tag=request.form['tag']).first()
            if e is None:
                e = Entries(user_id=current_user.id,
                            text=request.form['entry'])
            if t is None:
                t = Tags(tag=request.form['tag'])
            e.tags.append(t)
            db.session.add(e)
        db.session.commit()
    uTags = Tags.query.join(
        Entries.tags).filter(Entries.user_id == current_user.id).all()
    entryList = Entries.query.join(
        Tags.entries).filter_by(user_id=current_user.id)
    listsByTag = {}
    for t in uTags:
        listsByTag[t.tag] = entryList.filter(Tags.tag == t.tag).all()
    return render_template('index.html', list=listsByTag)
Exemple #14
0
def add_record(filename, tags):
    """Temporary method for adding records until I make a simple CMS."""
    db.create_all()

    if tags:
        for tag in tags.split(","):
            db_insert = Tags(name=tag)
            db.session.add(db_insert)
            db.session.commit()

    if filename:
        import csv
        with open(filename, "r") as file:
            reader = csv.DictReader(file)
            for row in reader:
                print(row)
                kwargs = {key: value for (key, value) in row.items()}
                kwargs["tags"] = [
                    Tags.query.filter_by(name=tag).first()
                    for tag in kwargs["tags"].split(",")
                ]
                db_insert = Post(**kwargs)
                db.session.add(db_insert)
                db.session.commit()
Exemple #15
0
def manage():

    header = {
        "title": "Admin page",
        "subtitle": "Manage your blog!",
        "image_path": "manage_bg.jpg",
        "needed": True,
        "dashboard_flash": True
    }

    posts = Blogpost.query.order_by(Blogpost.date_posted.desc()).all()
    tags = Tags.query.all()

    form = TagForm()

    #if post request to edit form and is validated
    if form.validate_on_submit():

        app.logger.info('tag to be added')

        tag = Tags(name=form.name.data)
        db.session.add(tag)
        db.session.commit()

        #flash message, article has been updated
        flash('tag uploaded', 'success')

        #redirect
        return redirect(url_for('manage'))

    #load template with articles
    return render_template('manage.html',
                           posts=posts,
                           header=header,
                           tags=tags,
                           form=form)
def postQuestion():
    if (not session or not session['loggedin']):
        return redirect(url_for('index'))

    if (request and request.method == 'POST'):
        title = request.form['title']
        body = request.form['content']
        code = request.form['code']
        tagstring = request.form['tags']
        tags = tagstring.split(';')

        new_row = Questions(title, body, code, session['userid'])
        question_id = new_row.question_id
        db.session.add(new_row)

        for tag in tags:
            new_tag = Tags(tag, question_id)
            db.session.add(new_tag)

        db.session.commit()
        # return redirect(url_for("answers/"+str(2)))
        return answers(question_id)
    else:
        return render_template('question_post.html', title="Ask Question")
Exemple #17
0
def get_sample_data():

    data = []

    ################# Users #################

    test = User(username='******',
                email='*****@*****.**',
                password_hash=generate_password_hash('password'),
                date_created=datetime.now(),
                last_login=datetime.now())
    guest = User(username='******',
                 email='*****@*****.**',
                 password_hash=generate_password_hash('password'),
                 date_created=datetime.now(),
                 last_login=datetime.now())
    mazx = User(username='******',
                email='*****@*****.**',
                password_hash=generate_password_hash('password'),
                date_created=datetime.now(),
                last_login=datetime.now())

    data.append(test)
    data.append(guest)
    data.append(mazx)

    ################# Followers #################

    test_follow_guest = Followers(date_followed=datetime.now(),
                                  follower=1,
                                  followed=2)

    data.append(test_follow_guest)

    ################# Notes #################

    test_note = Notes(date_created=datetime.now(),
                      last_edited=datetime.now(),
                      private=True,
                      parent_folder_id=0,
                      title='This is a test note',
                      body='This is a test content',
                      body_markdown='This is a test content',
                      user_id=1)

    guest_note = Notes(date_created=datetime.now(),
                       last_edited=datetime.now(),
                       private=False,
                       parent_folder_id=0,
                       title='This is a guest note',
                       body='This is a guest content',
                       body_markdown='This is a guest content',
                       user_id=2)

    data.append(test_note)
    data.append(guest_note)

    ################# Folders #################

    test_folder = Folders(folder_name='Test Folder', user_id=1)

    guest_folder = Folders(folder_name='Guest Folder', user_id=2)

    data.append(test_folder)
    data.append(guest_folder)

    ################# Notes_Permissions #################

    test_note_allow_mazx = Notes_Permissions(date_shared=datetime.now(),
                                             note_id=1,
                                             user_id=3)

    data.append(test_note_allow_mazx)

    ################# Notes_tag #################

    test_note_test_tag = Notes_tag(note_id=1, tag_id=1)

    guest_note_guest_tag = Notes_tag(note_id=2, tag_id=2)

    data.append(test_note_test_tag)
    data.append(guest_note_guest_tag)

    ################# Tags #################

    test_tag = Tags(user_id=1, tag='testtag')

    guest_tag = Tags(user_id=2, tag='guesttag')

    data.append(test_tag)
    data.append(guest_tag)

    ########################################

    return data
Exemple #18
0
def addStory(updateDat):
    assert 'story' in updateDat
    story = updateDat['story']

    assert 'name' in story
    assert 'auth' in story
    assert 'fname' in story
    assert 'file' in story
    assert 'desc' in story
    assert 'tags' in story

    data = DataURI(story['file'])

    dathash = getHash(data.data).lower()
    have = Story.query.filter(Story.hash == dathash).scalar()

    if have:
        # print("Have file already!")
        return getResponse(
            "A file with that MD5 hash already exists! Are you accidentally adding a duplicate?",
            True)

    have = Story.query.filter(Story.title == story['name']).scalar()
    if have:
        orig_name = story['name']
        loop = 2
        while have:
            print("Have story with that name ('%s')!" % story['name'])
            story['name'] = orig_name + " (%s)" % loop
            have = Story.query.filter(Story.title == story['name']).scalar()
            loop += 1
        print("Story added with number in name: '%s'" % story['name'])

    if len(story['name']) > 80:
        return getResponse("Maximum story title length is 80 characters!",
                           True)
    if len(story['name']) < 3:
        return getResponse("Minimum story title length is 3 characters!", True)
    if len(story['auth']) < 5:
        return getResponse("Minimum story author name length is 5 characters!",
                           True)
    if len(story['auth']) > 60:
        return getResponse(
            "Maximum story author name length is 60 characters!", True)
    if len(story['desc']) < 30:
        return getResponse(
            "Minimum story description length is 30 characters!", True)
    if len(story['desc']) > 500:
        return getResponse(
            "Maximum story description length is 500 characters!", True)

    fspath = saveFile(data.data, story['fname'])

    stags = ["-".join(itm_tags.split(" ")) for itm_tags in story['tags']]
    stags = [bleach.clean(tag, tags=[], strip=True) for tag in stags]

    # print("Author: ", story['auth'])
    # print("stags: ", story['tags'])
    # print("stags: ", stags)

    post_date = datetime.datetime.now()
    if 'ul_date' in story and isinstance(story['ul_date'], datetime.datetime):
        post_date = story['ul_date']

    new = Story(
        title=bleach.clean(story['name'], tags=[], strip=True),
        srcfname=story['fname'],
        description=markdown.markdown(bleach.clean(story['desc'], strip=True)),
        fspath=fspath,
        hash=dathash,
        # author      = [story['auth']],
        # tags        = stags,
        pub_date=post_date)

    [new.tags.append(Tags(tag=tag)) for tag in stags]
    new.author.append(
        Author(name=bleach.clean(story['auth'], tags=[], strip=True)))

    db.session.add(new)
    db.session.commit()

    flash('Your story has been added! Thanks for posting your content!')
    return getResponse("Story added", error=False)
Exemple #19
0
def pre_fill_db():
    try:
        moods = []
        moods.append(
            Mood(mood_name='Positive')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        moods.append(
            Mood(mood_name='Neutral')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        moods.append(
            Mood(mood_name='Negative')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        # db.session.add(moods[0])
        # db.session.add(moods[1])
        # db.session.add(moods[2])
        m = len(moods)
        for y in moods:
            db.session.add(moods[m])
            m += 1

        tags = []
        tags.append(
            Tags(tag_name='Unknown')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        tags.append(
            Tags(tag_name='Work')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        tags.append(
            Tags(tag_name='Family')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        tags.append(
            Tags(tag_name='Friends')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        tags.append(
            Tags(tag_name='Development')
        )  #, is_active=1, created_by=1, created_date=datetime.now()))
        db.session.add(tags[0])
        db.session.add(tags[1])
        db.session.add(tags[2])
        db.session.add(tags[3])

        notes = []
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        notes.append(
            Note(mood_id=random.randrange(1, 3),
                 my_note=lorem.paragraph(),
                 created_by=1,
                 create_date=random_date()))
        db.session.add(notes[0])
        db.session.add(notes[1])
        db.session.add(notes[2])
        db.session.add(notes[3])
        db.session.add(notes[4])
        db.session.add(notes[5])
        db.session.add(notes[6])
        db.session.add(notes[7])
        db.session.add(notes[8])
        db.session.add(notes[9])

        # tagnote = []
        # tagnote.append(tags_notes(tags_id=1,notes_id=1))
        # tagnote.append(tags_notes(tags_id=2,notes_id=1))
        # tagnote.append(tags_notes(tags_id=3,notes_id=1))
        # tagnote.append(tags_notes(tags_id=4,notes_id=1))
        # tagnote.append(tags_notes(tags_id=2,notes_id=2))
        # tagnote.append(tags_notes(tags_id=3,notes_id=2))
        # tagnote.append(tags_notes(tags_id=4,notes_id=2))
        # tagnote.append(tags_notes(tags_id=3,notes_id=3))
        # tagnote.append(tags_notes(tags_id=4,notes_id=3))
        # tagnote.append(tags_notes(tags_id=4,notes_id=4))
        # db.session.add(tagnote[0])
        # db.session.add(tagnote[1])
        # db.session.add(tagnote[2])
        # db.session.add(tagnote[3])
        # db.session.add(tagnote[4])
        # db.session.add(tagnote[5])
        # db.session.add(tagnote[6])
        # db.session.add(tagnote[7])
        # db.session.add(tagnote[8])
        # db.session.add(tagnote[9])

        ideas = []
        ideas.append(
            Idea(name=lorem.sentence(),
                 description=lorem.paragraph(),
                 is_active=random.choice([True, False]),
                 created_by=1,
                 create_date=random_date()))
        ideas.append(
            Idea(name=lorem.sentence(),
                 description=lorem.paragraph(),
                 is_active=random.choice([True, False]),
                 created_by=1,
                 create_date=random_date()))
        db.session.add(ideas[0])
        db.session.add(ideas[1])

        ideanotes = []
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=1,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=1,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=1,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=1,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=1,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=2,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=2,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=2,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=2,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        ideanotes.append(
            IdeaNotes(title=lorem.sentence(),
                      description=lorem.paragraph(),
                      is_active=random.choice([True, False]),
                      idea_id=2,
                      created_by=1,
                      create_date=random_date(),
                      follow_up_date=datetime.now() +
                      timedelta(days=random.random())))
        db.session.add(ideanotes[0])
        db.session.add(ideanotes[0])
        db.session.add(ideanotes[1])
        db.session.add(ideanotes[2])
        db.session.add(ideanotes[3])
        db.session.add(ideanotes[4])
        db.session.add(ideanotes[5])
        db.session.add(ideanotes[6])
        db.session.add(ideanotes[7])
        db.session.add(ideanotes[8])
        db.session.add(ideanotes[9])

        db.session.commit()
    # except ValueError:
    except ValueError as e:
        # log.error("Creating mood: %s", ValueError)
        # print(db.error)
        print(e)
        db.session.rollback()
Exemple #20
0
def submit():
    if request.method == 'POST':
        name = request.form['name']
        screenshot = ''
        if 'screenshot' in request.files:
            f = request.files['screenshot']
            img = Image.open(f)
            path = "static/img/" + f.filename
            img.save(path)
            screenshot = "static/img/" + f.filename
        num_developers = request.form['num_developers']
        developers = request.form['developers']
        github_usernames = request.form['github_usernames']
        description = request.form['description']
        link = request.form['link']
        github_repo = request.form['github_repo']
        long_description = request.form['long_description']
        tags = request.form['tags']
        program_attended = request.form['program_attended']
        email = request.form['email']
        # for i in range (1, NUM_TAGS):
        # tag was selected
        # print("HI")
        #if(request.form['tag-'+str(i)]=="true"):
        #db.session.add(Tags(tag="Python", projID=1,color='#FF00FF'))
        #db.session.commit()
        #db.session.close()
        if name and screenshot and num_developers and developers and \
            description and long_description and program_attended and email:
            print(request.form)
            try:
                db.session.add(
                    Project(name=name,
                            screenshot=screenshot,
                            num_developers=num_developers,
                            developers=developers,
                            github_usernames=github_usernames,
                            description=description,
                            link=link,
                            github_repo=github_repo,
                            long_description=long_description,
                            program_attended=program_attended,
                            email=email,
                            status="pending",
                            isDeleted='false',
                            is_featured='false'))
                db.session.commit()
                db.session.close()

                query = "SELECT max(id) FROM project;"
                projectID_row = db.session.execute(query)
                for row in projectID_row:
                    projectID = row[0]

                tags_separated = tags.split(',')
                for tag in tags_separated:
                    query_color = "SELECT DISTINCT color FROM tags WHERE tag='" + tag + "';"
                    color_rows = db.session.execute(query_color)
                    for row in color_rows:
                        color = row[0]
                    db.session.add(
                        Tags(tag=tag, color=color, projectID=projectID))

                db.session.commit()
                db.session.close()

                email = Message(
                    subject=CONFIRMATION_MAIL_SUBJECT,
                    body=CONFIRMATION_MAIL_BODY,
                    sender=CONFIRMATION_MAIL_SENDER,
                    # recipients=[request.form['email']])
                    recipients=['*****@*****.**'])
                mail.send(email)
                return json.dumps({'html': '<span>Project Added</span>'})
            except Exception as e:
                db.session.rollback()
                print("angery")
                print(str(e))
                return json.dumps({'error': str(e)})
        else:
            return json.dumps(
                {'html': '<span>Enter the required fields</span>'})
    else:
        allTags = "SELECT DISTINCT tag,color from tags"
        tagsResult = db.session.execute(allTags)
        return render_template('form.html', tags=tagsResult)
Exemple #21
0
def tag_list(page=None):
    if page is None:
        page = 1
    tags = Tags.get_ten_page(page=page)
    return render_template("admin/tag_list.html", tags=tags)