コード例 #1
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def user_article_mine_modify(id):
    form = ArticleInfoForm()
    article_tags = ArticleTag.query.all()
    form.article_tag.choices = [(tag.id, tag.name) for tag in article_tags]
    form.article_cover.validators = [FileAllowed(IMAGES, '只允许图像格式为:%s' % str(IMAGES)), ]
    article = Article.query.get_or_404(id)
    if request.method == "GET":
        form.article_title.data = article.title
        form.article_abstract.data = article.abstract
        form.article_privacy.data = article.privacy
        form.article_tag.data = article.tag_id
        form.article_recmm.data = article.recommed
    if form.validate_on_submit():
        article.title = form.article_title.data
        article.abstract = form.article_abstract.data
        article.privacy = form.article_privacy.data
        article.tag_id = int(form.article_tag.data)
        article.recommed = int(form.article_recmm.data)
        # 保存新的封面图像
        fs = request.files.get(form.article_cover.name)
        if fs.filename != '':
            # 删除原来的封面图像
            coverpath = photosSet.path(filename=article.cover)
            if os.path.isfile(coverpath):
                os.remove(coverpath)
            covername = secure_filename_with_uuid(fs.filename)
            subfolder = session.get("user_name") + '/' + article.uuid
            article.cover = photosSet.save(fs, folder=subfolder, name=covername)
        db.session.add(article)
        db.session.commit()
        return redirect(url_for('home.user_article_mine', page=1))
    return render_template("home/user_article_mine_modify.html", form=form)
コード例 #2
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def recieve_file():
    if request.method == "POST":
        # 获取CKeditor的JS回调函数reference
        CKEditorFuncNum = request.args.get('CKEditorFuncNum')
        # 获取当前正在编辑的文章ID
        articleId = request.args.get('aid')
        # 从数据库查询正在编辑的文章
        article = Article.query.get_or_404(int(articleId))
        # 获取POST请求中的files中的FileStorage对象,并保存到指定的目录
        fs = request.files.get('upload')
        if fs.filename != '':
            try:
                subfolder = session.get('user_name') + '/' + article.uuid
                newfname = secure_filename_with_uuid(fs.filename)
                fname = filesSet.save(fs, folder=subfolder, name=newfname)
                # 获取刚刚保存的文件的url
                file_url = imgsSet.url(filename=fname)
                # 把文件的url返回给CKEditor
                message = '文件上传成功!'
                # 把文件的url返回给CKEditor
                ret_js = "<script type='text/javascript'> " \
                         "window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');" \
                         "</script>" % (CKEditorFuncNum, file_url, message)
                return ret_js
            except UploadNotAllowed:
                message = '扩展名不正确!只接受:' + str(AUDIO + DOCUMENTS + ARCHIVES)
    return message
コード例 #3
0
def recieve_dragged_pasted():
    if request.method == 'POST':
        # 获取POST请求中的files中的FileStorage对象,并保存到指定的目录
        keys = request.files.keys()
        articleId = request.args.get('aid')
        article = Article.query.get_or_404(int(articleId))
        for key in keys:
            fs = request.files.get(key)
            if fs.filename != '':
                if request.args.get('type') == 'images':
                    uploadSet = imgsSet
                if request.args.get('type') == 'files':
                    uploadSet = filesSet
                try:
                    subfolder = session.get('user_name') + '/' + article.uuid
                    newfname = secure_filename_with_uuid(fs.filename)
                    fname = uploadSet.save(fs, folder=subfolder, name=newfname)
                    # 获取刚刚保存的文件的url
                    file_url = uploadSet.url(filename=fname)
                    # 把文件的url返回给CKEditor
                    res = {
                        "uploaded": 1,
                        "fileName": fname,
                        "url": file_url,
                    }
                    return jsonify(res)
                except UploadNotAllowed:
                    message = '扩展名不正确!只接受:' + str(IMAGES + AUDIO + ARCHIVES +
                                                  DOCUMENTS)
                    res = {"uploaded": 0, "error": {"message": message}}
                    return jsonify(res)
        return 'ok'
コード例 #4
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def user_info():
    form = InfoForm()
    user = User.query.get_or_404(int(session.get("user_id")))
    if request.method == "GET":
        form.user_jianjie.data = user.jianjie
    if form.validate_on_submit():
        old_name = user.name
        user.name = form.data["user_name"]
        user.email = form.data["user_email"]
        user.phone = form.data["user_phone"]
        user.jianjie = form.user_jianjie.data
        filestorage = request.files["user_face"]
        # 判断用户是否上传了新的头像文件
        if filestorage.filename != "":
            # 如果上传了符合要求的新的头像文件,则首先删除旧的,再保存新的
            userface_path = photosSet.path(filename=user.face, folder=old_name)
            os.remove(path=userface_path)
            # 更新 user.face 中保存的头像文件名
            user.face = secure_filename_with_uuid(filestorage.filename)
            photosSet.save(storage=filestorage, folder=old_name, name=user.face)

        # 如果用户修改了用户名, 就修改用户的上传文件夹
        if old_name != user.name:
            os.rename(os.path.join(app.config["UPLOADS_FOLDER"], old_name),
                      os.path.join(app.config["UPLOADS_FOLDER"], user.name))
        # 更新数据项
        db.session.add(user)
        db.session.commit()
        session["user_name"] = user.name
        session["user_id"] = user.id
        return redirect(url_for("user_detail"))
    return render_template("user_info.html", user=user, form=form)
コード例 #5
0
def user_regist():
    form = RegistForm()
    if form.validate_on_submit():
        # 查看用户名是否已经存在
        user_name = form.user_name.data
        user_x = User.query.filter_by(name=user_name).first()
        if user_x:
            flash("用户名已经存在!", category='err')
            return render_template('user_regist.html', form=form)
        # 如果用户不存在,创建一个用户类的实例
        user = User()
        user.name = form.user_name.data
        user.pwd = generate_password_hash(form.user_pwd.data)
        user.email = form.data['user_email']
        user.phone = form.user_phone.data
        user.jianjie = form.user_jianjie.data
        user.uuid = str(uuid.uuid4().hex)[0:10]  # 给每个用户分配一个10个字符的身份标识符
        filestorage = request.files["user_face"]
        user.face = secure_filename_with_uuid(filestorage.filename)
        # 保存用户头像文件,执行插入操作
        try:
            photosSet.save(storage=filestorage,
                           folder=user.name,
                           name=user.face)
            db.session.add(user)
            db.session.commit()
            flash("用户注册成功!", category='ok')
            return redirect(url_for("user_login", username=user.name))
        except UploadNotAllowed:
            flash("头像文件格式不对!", category='err')
            return render_template('user_regist.html', form=form)
    return render_template('user_regist.html', form=form)
コード例 #6
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def user_regist():
    form = RegistForm()
    if form.validate_on_submit():
        # 查看用户名是否已经存在
        user_name = form.user_name.data
        user_x = query_user_by_name(user_name)
        if user_x:
            flash("用户名已经存在!", category='err')
            return render_template('user_regist.html', form=form)
        # 如果用户不存在,执行注册
        user = User()
        user.name = form.user_name.data
        user.pwd = form.user_pwd.data
        user.email = form.data['user_email']
        user.age = form.user_edge.data
        user.birthday = form.data["user_birthday"]
        filestorage = request.files["user_face"]
        user.face = secure_filename_with_uuid(filestorage.filename)
        # 如果用户不存在,执行插入操作
        insert_user_to_db(user)
        # 保存用户头像文件
        try:
            photosSet.save(storage=filestorage,
                           folder=user.name,
                           name=user.face)
            flash("用户注册成功!", category='ok')
            return redirect(url_for("user_login", username=user.name))
        except UploadNotAllowed:
            flash("头像文件格式不对!", category='err')
            return render_template('user_regist.html', form=form)

    return render_template('user_regist.html', form=form)
コード例 #7
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def article_create():
    form = ArticleInfoForm()
    article_tags = ArticleTag.query.all()
    form.article_tag.choices = [(tag.id, tag.name) for tag in article_tags]
    if form.validate_on_submit():
        article = Article()
        article.title = form.article_title.data
        article.abstract = form.article_abstract.data
        article.privacy = form.article_privacy.data
        article.tag_id = form.article_tag.data
        article.recommed = form.article_recmm.data
        article.content = ""
        article.user_id = int(session.get("user_id"))
        article.uuid = str(uuid.uuid4().hex)[0:15]
        fs = request.files.get(form.article_cover.name)
        if fs.filename != '':
            covername = secure_filename_with_uuid(fs.filename)
            subfolder = session.get("user_name") + '/' + article.uuid
            article.cover = photosSet.save(fs,
                                           folder=subfolder,
                                           name=covername)
        db.session.add(article)
        db.session.commit()
        return redirect(url_for("home.article_write", aid=article.id))
    return render_template("home/article_create.html", form=form)
コード例 #8
0
def user_info():
    form = InfoForm()
    user = query_user_by_name(session.get("user_name"))
    if form.validate_on_submit():
        old_name = user.name
        user.name = form.data["user_name"]
        user.email = form.data["user_email"]
        user.age = form.data["user_edge"]
        user.birthday = form.data["user_birthday"]
        filestorage = form.user_face.data
        # 判断用户是否上传了新的头像文件
        if filestorage.filename != "":
            # 如果上传了符合要求的新的头像文件,则首先删除旧的,再保存新的
            user_folder = os.path.join(app.config["UPLOADS_FOLDER"], old_name)
            os.remove(path=os.path.join(user_folder, user.face))
            # 更新 user.face 中保存的头像文件名
            user.face = secure_filename_with_uuid(filestorage.filename)
            filestorage.save(os.path.join(user_folder, user.face))

        # 如果用户修改了用户名, 就修改用户的上传文件夹
        if old_name != user.name:
            os.rename(os.path.join(app.config["UPLOADS_FOLDER"], old_name),
                      os.path.join(app.config["UPLOADS_FOLDER"], user.name))
        # 更新数据项
        update_user_by_name(old_name, user)
        session["user_name"] = user.name
        return redirect(url_for("user_detail"))
    return render_template("user_info.html", user=user, form=form)
コード例 #9
0
def user_info():
    form = InfoForm()
    user = query_user_by_name(session.get("user_name"))
    if form.validate_on_submit():
        old_name = user.name
        user.name = form.data["user_name"]
        user.email = form.data["user_email"]
        user.age = form.data["user_edge"]
        user.birthday = form.data["user_birthday"]
        filestorage = request.files["user_face"]
        # 判断用户是否上传了新的头像文件
        if filestorage.filename != "":
            # 检查用户上传的头像文件名是否符合要求
            if not check_files_extension([form.user_face.data.filename],
                                         ALLOWED_IMAGE_EXTENSIONS):
                flash("头像文件扩展名不对!", category='err')
                return redirect(url_for("user_info"))
            # 如果上传了符合要求的新的头像文件,则首先删除旧的,再保存新的
            user_folder = os.path.join(app.config["UPLOADS_FOLDER"], old_name)
            os.remove(path=os.path.join(user_folder, user.face))
            # 更新 user.face 中保存的头像文件名
            user.face = secure_filename_with_uuid(filestorage.filename)
            filestorage.save(os.path.join(user_folder, user.face))

        # 如果用户修改了用户名, 就修改用户的上传文件夹
        if old_name != user.name:
            os.rename(os.path.join(app.config["UPLOADS_FOLDER"], old_name),
                      os.path.join(app.config["UPLOADS_FOLDER"], user.name))
        # 更新数据项
        update_user_by_name(old_name, user)
        session["user_name"] = user.name
        return redirect(url_for("user_detail"))
    return render_template("user_info.html", user=user, form=form)
コード例 #10
0
def user_regist():
    form = RegistForm()
    if form.validate_on_submit():
        # 查看用户名是否已经存在
        user_name = form.user_name.data
        user_x = query_user_by_name(user_name)
        if user_x:
            flash("用户名已经存在!", category='err')
            return render_template('user_regist.html', form=form)
        # 如果用户不存在,执行注册
        user = User()
        user.name = form.user_name.data
        user.pwd = form.user_pwd.data
        user.email = form.data['user_email']
        user.age = form.user_edge.data
        user.birthday = form.data["user_birthday"]
        filestorage = request.files["user_face"]
        user.face = secure_filename_with_uuid(filestorage.filename)
        # 如果用户不存在,执行插入操作
        insert_user_to_db(user)
        # 保存用户头像文件
        user_folder = os.path.join(app.config["UPLOADS_FOLDER"], user.name)
        create_folder(user_folder)
        filestorage.save(os.path.join(user_folder, user.face))
        flash("用户注册成功!", category='ok')
        return redirect(url_for("user_login", username=user.name))
    return render_template('user_regist.html', form=form)
コード例 #11
0
def user_info():  # 修改个人信息
    user = query_user_by_name(session.get("user_name"))

    # 打开修改信息页面,将原来信息展示出来,消息回填

    form = InfoForm()
    if form.validate_on_submit():

        current_login_name = session.get("user_name")
        old_name = user.name
        new_name = request.form["user_name"]

        query_user = query_user_by_name(new_name)
        if query_user == None or current_login_name == query_user.name:  # 如果数据库没有这个用户名或者当前登录的用户名和更改的用户名一样(本人操作),都可以更新个人信息
            user.name = request.form["user_name"]
            user.email = request.form["user_email"]
            user.age = request.form["user_age"]
            user.birthday = request.form["user_birthday"]
            filestorage = request.files["user_face"]  # 获取头像文件
            # filestorage = form.user_face.data  # 获取头像文件
            if filestorage.filename != "":
                # # 检查用户上传的头像文件名是否符合要求
                # if not check_files_extension([form.user_face.data.filename], ALLOWED_IMAGEEXTENSIONS):
                #     flash("头像文件格式错误!", category="err")
                #     return redirect(url_for("user_info"))
                # 若果上传了新的头像文件,首先删除旧的,再保存新的
                # user_folder = os.path.join(app.config["UPLOADS_FOLDER"], old_name)
                # 删除就旧的头像
                # os.remove(path=os.path.join(user_folder, user.face))
                # 获取旧头像的存储路径
                userface_path = photosSet.path(filename=user.face,
                                               folder=old_name)
                # 删除就旧的头像
                os.remove(userface_path)

                # 保存新的
                user.face = secure_filename_with_uuid(filestorage.filename)
                # filestorage.save(os.path.join(user_folder, user.face))
                photosSet.save(storage=filestorage,
                               folder=old_name,
                               name=user.face)
                pass
            # 判断是否修改了用户名:如果修改了则同时修改用户上传资源文件夹
            if old_name != new_name:
                os.rename(os.path.join(app.config["UPLOADS_FOLDER"], old_name),
                          os.path.join(app.config["UPLOADS_FOLDER"], new_name))
                pass
            update_user_by_name(old_name, user)
            flash(message="用户信息已更新!", category="ok")
            session.pop("user_name", None)  # 修改密码后需要重新登录,然后清除session中的数据
            session["user_name"] = user.name
            return redirect(url_for("user_detail"))
        else:
            flash(message="用户名已存在!", category="err")

    return render_template("user_info.html", user=user, form=form)
コード例 #12
0
def user_regist():  # 注册
    form = RegistForm()
    if form.validate_on_submit(
    ):  # 检查提交方式是否为post 验证forms.py定义的validators 验证是否通过
        # 检查用户上传的头像文件名是否符合要求
        if not check_files_extension([form.user_face.data.filename],
                                     ALLOWED_IMAGEEXTENSIONS):
            flash("头像文件格式错误!", category="err")
            return render_template("user_regist.html", form=form)
        # 查看用户是否存在
        user_name = form.user_name.data
        user_one = query_user_by_name(user_name)
        if user_one:
            # 返回注册界面,重新注册
            flash("用户名已存在!", category="err"
                  )  # Flashes a message to the next request 闪现一条消息到下一次消息请求

            return render_template("user_regist.html", form=form)

        # print("form", form.user_name.data)
        # print("form", form.data)
        # print("form", form.data["user_name"])
        # print("request.form", request.form)
        user = User()
        # user.name = request.form["user_name"]
        user.name = form.user_name.data
        # user.pwd = request.form["user_pwd"]
        user.pwd = form.user_pwd.data
        # user.age = request.form["user_age"]
        user.age = form.user_age.data
        # user.birthday = request.form["user_birthday"]
        user.birthday = form.user_birthday.data
        # user.email = request.form["user_email"]
        user.email = form.user_email.data
        # user.face = request.form["user_face"]
        # user.face = form.user_face.data
        # filerstorage=form.user_face.data
        filerstorage = request.files["user_face"]  # 获取头像文件
        user.face = secure_filename_with_uuid(
            filerstorage.filename
        )  # secure_filename 文件名安全性检测,如果文件名有特殊字符,会将特殊字符转义,没有就返回原文件名
        # print(user.face)

        # 如果不存在执行插入操作
        # 插入一条数据
        instert_user_to_db(user)
        # 保存用户头像文件
        user_folder = os.path.join(app.config["UPLOADS_FOLDER"], user.name)
        create_folder(user_folder)  # 创建用户文件夹
        filerstorage.save(os.path.join(user_folder, user.face))
        flash("注册成功!", category="ok")
        # username作为查询参数带到url中去
        # 重定向页面 生成url 执行 user_login 函数 跳转到登录界面
        return redirect(url_for("user_login", username=user.name))
    return render_template("user_regist.html", form=form)
コード例 #13
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def album_upload():
    form = AlbumUploadForm()
    albums = Album.query.filter_by(user_id=session.get("user_id")).all()
    form.album_title.choices = [(item.id, item.title) for item in albums]
    if len(form.album_title.choices) < 1:
        flash(message="请先创建一个相册!再上传照片", category='err')
        return redirect(url_for("album_create"))
    if request.method == "POST":
        # 通过 files.getlist() 获得上传的 FileStorage 文件对象列表
        fses = request.files.getlist("album_upload")
        # 检查文件扩展名,将合格的文件过滤出来
        valid_fses = check_filestorages_extension(fses, ALLOWED_IMAGE_EXTENSIONS)
        if len(valid_fses) < 1:
            flash(message="只允许上传文件类型:" + str(ALLOWED_IMAGE_EXTENSIONS), category='err')
            return redirect(url_for("album_upload"))
        else:
            files_url = []
            album_cover = ''
            # 开始遍历保存每一个合格文件
            for fs in valid_fses:
                album_title = ''
                for id, title in form.album_title.choices:
                    if id == form.album_title.data:
                        album_title = title
                folder = session.get("user_name") + '/' + album_title
                name_orig = secure_filename_with_uuid(fs.filename)
                fname = photosSet.save(fs, folder=folder, name=name_orig)
                ts_path = photosSet.config.destination + '/' + folder
                # 创建并保存缩略图
                name_thumb = create_thumbnail(path=ts_path, filename=name_orig, base_width=300)
                # 创建并保存展示图
                name_show = create_show(path=ts_path, filename=name_orig, base_width=800)
                # 把产生的Photo对象保存到数据库
                photo = Photo(origname=name_orig, showname=name_show, thumbname=name_thumb,
                              album_id=form.album_title.data)
                db.session.add(photo)
                db.session.commit()
                # 设置封面文件
                album_cover = photo.thumbname
                # 获取刚才保存的缩略图文件的url
                furl = photosSet.url(folder + '/' + name_thumb)
                files_url.append(furl)

            album = Album.query.filter_by(id=form.album_title.data).first()
            album.photonum += len(valid_fses)
            album.cover = album_cover
            db.session.add(album)
            db.session.commit()
            message = "成功保存:" + str(len(valid_fses)) + "张图像; "
            message += "当前相册共有:" + str(album.photonum) + "张图像"
            flash(message=message, category='ok')
            return render_template("album_upload.html", form=form, files_url=files_url)
    return render_template("album_upload.html", form=form)
コード例 #14
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def album_upload():
    form = AlbumSelectForm()
    albums = Album.query.filter_by(user_id=session.get("user_id")).all()
    form.album_title.choices = [(item.id, item.title) for item in albums]
    if len(form.album_title.choices) < 1:
        flash(message="请先创建一个相册!再上传照片", category='err')
        return redirect(url_for("album_create"))
    if request.method == "POST":
        fs_keys = request.files.keys()
        album_id = int(request.args.get('aid'))
        for key in fs_keys:
            fs = request.files.get(key)
            album_title = ''
            for id, title in form.album_title.choices:
                if id == album_id:
                    album_title = title
            folder = session.get("user_name") + '/' + album_title
            name_orig = secure_filename_with_uuid(fs.filename)
            fname = photosSet.save(fs, folder=folder, name=name_orig)
            ts_path = photosSet.config.destination + '/' + folder
            # 创建并保存缩略图
            name_thumb = create_thumbnail(path=ts_path,
                                          filename=name_orig,
                                          base_width=300)
            # 创建并保存展示图
            name_show = create_show(path=ts_path,
                                    filename=name_orig,
                                    base_width=800)
            # 把产生的Photo对象保存到数据库
            photo = Photo(origname=name_orig,
                          showname=name_show,
                          thumbname=name_thumb,
                          album_id=album_id)
            db.session.add(photo)
            db.session.commit()
            # 设置封面文件
            album_cover = photo.thumbname
        # 更新相册的信息
        album = Album.query.get_or_404(album_id)
        album.photonum += 1
        album.cover = album_cover
        db.session.add(album)
        db.session.commit()
        # message = "成功保存:" + str(1) + "张图像; "
        # message += "当前相册共有:" + str(album.photonum) + "张图像"
        # flash(message=message, category='ok')
        return redirect(url_for('album_upload'))
    return render_template("album_upload_dropzone.html", form=form)
コード例 #15
0
ファイル: views.py プロジェクト: edzq/FlaskProject
def user_album_mine_photo_add(id):
    album = Album.query.get_or_404(id)
    if request.method == 'GET':
        folder = album.user.name + '/' + album.title
        for photo in album.photos:
            photo.url = photosSet.url(folder + '/' + photo.thumbname)
    if request.method == "POST":
        # 通过 files.getlist() 获得上传的 FileStorage 文件对象列表
        fses = request.files.getlist("album_upload")
        # 检查文件扩展名,将合格的文件过滤出来
        valid_fses = check_filestorages_extension(fses,
                                                  ALLOWED_IMAGE_EXTENSIONS)
        if len(valid_fses) < 1:
            flash(message="只允许上传文件类型:" + str(ALLOWED_IMAGE_EXTENSIONS),
                  category='err')
            return redirect(url_for("user_album_mine_adddel", id=id))
        else:
            # 开始遍历保存每一个合格文件
            for fs in valid_fses:
                folder = session.get("user_name") + '/' + album.title
                name_orig = secure_filename_with_uuid(fs.filename)
                fname = photosSet.save(fs, folder=folder, name=name_orig)
                ts_path = photosSet.config.destination + '/' + folder
                # 创建并保存缩略图
                name_thumb = create_thumbnail(path=ts_path,
                                              filename=name_orig,
                                              base_width=300)
                # 创建并保存展示图
                name_show = create_show(path=ts_path,
                                        filename=name_orig,
                                        base_width=800)
                # 把产生的Photo对象保存到数据库
                photo = Photo(origname=name_orig,
                              showname=name_show,
                              thumbname=name_thumb,
                              album_id=album.id)
                db.session.add(photo)
                db.session.commit()
            album.photonum += len(valid_fses)
            db.session.add(album)
            db.session.commit()
            message = "成功保存:" + str(len(valid_fses)) + "张图像; "
            message += "当前相册共有:" + str(album.photonum) + "张图像"
            flash(message=message, category='ok')
        return redirect(url_for("user_album_mine_photo_add", id=id))
    return render_template('user_album_mine_adddel.html',
                           album=album,
                           form=PhotoAddForm())
コード例 #16
0
def album_upload():
    print(current_user)
    form = AlbumUploadForm()
    # 根据user_id筛选出相册
    items = Album.query.filter_by(user_id=session.get('user_id'))
    form.album_title.choices = [(item.id, item.title) for item in items]
    if len(form.album_title.choices) < 1:
        flash('请先创建相册,再上传图片', 'danger')
        return redirect(url_for('main.album_create'))
    print('album_upload:', request.method)
    if request.method == 'POST':
        # 同伙getlist方法获取FileStorage文件列表
        fs = request.files.getlist('main.album_upload')
        # 检查文件扩展名,将合格的文件过滤出来
        valid_fs = check_filestorage_extension(
            fs, allowd_extensions=ALLOWED_IMAGE_EXTENSION)
        if len(valid_fs) < 1:
            flash('只允许上传类型为:' + str(ALLOWED_IMAGE_EXTENSION), 'danger')
            return redirect(url_for('main.album_upload'))
        else:
            # 开始遍历保存文件
            files_url = []
            album_cover = ''
            for fs in valid_fs:
                print('fs:', fs)
                # 第四步,使用UploadSet的save方法保存文件
                name_org = secure_filename_with_uuid(fs.filename)
                for id, title in form.album_title.choices:
                    if id == form.album_title.data:
                        album_title = title
                folder = current_user.name + '/' + album_title
                fname = photoSet.save(storage=fs, folder=folder, name=name_org)
                ts_path = photoSet.config.destination + '/' + folder
                #创建并保存缩略图
                name_thumb = create_thumbnail(path=ts_path,
                                              filename=name_org,
                                              base_width=100)
                #创建并保存展示图
                name_show = create_thumbnail(path=ts_path,
                                             filename=name_org,
                                             base_width=800)
                # 把产生的photo对象保存到数据库中
                photo = Photo(name_org=name_org,
                              name_show=name_show,
                              name_thumb=name_thumb,
                              album_id=form.album_title.data)
                db.session.add(photo)
                db.session.commit()
                #获取刚才保存的缩略图文件的url
                fs_url = photoSet.url(folder + '/' + name_thumb)
                # # 第五步,使用UploadSet的url方法获得文件的url
                # fs_url = photoSet.url(filename=fname)
                files_url.append(fs_url)
                # 设置封面文件
                photo.album_cover = photo.name_thumb
                print('fs_url:', fs_url)
            album = Album.query.filter_by(id=form.album_title.data).first()
            album.photonum += len(valid_fs)
            album.cover = album_cover
            db.session.add(album)
            db.session.commit()
            flash('成功保存了%s张图片' % str(len(valid_fs)), 'success')
            flash('当前相册共有%s张图片' % str(album.photonum), 'success')
            return render_template('album_upload.html',
                                   files_url=files_url,
                                   form=form)
    return render_template('album_upload.html', form=form)
コード例 #17
0
def user_regist():  # 注册
    form = RegistForm()
    if form.validate_on_submit(
    ):  # 检查提交方式是否为post 验证forms.py定义的validators 验证是否通过
        # 检查用户上传的头像文件名是否符合要求
        # if not check_files_extension([form.user_face.data.filename], ALLOWED_IMAGEEXTENSIONS):
        #     flash("头像文件格式错误!", category="err")
        #     return render_template("user_regist.html", form=form)
        # 查看用户是否存在
        user_name = form.user_name.data
        query_user_by_name = User.query.filter_by(name=user_name).first()
        if query_user_by_name:
            # 返回注册界面,重新注册
            flash("用户名已存在!", category="err"
                  )  # Flashes a message to the next request 闪现一条消息到下一次消息请求
            return render_template("user_regist.html", form=form)

        query_user_by_email = User.query.filter_by(
            email=form.user_email.data).first()
        if query_user_by_email:
            # 返回注册界面,重新注册
            flash("用户邮箱已被注册注册!", category="err"
                  )  # Flashes a message to the next request 闪现一条消息到下一次消息请求
            return render_template("user_regist.html", form=form)

        query_user_by_phone = User.query.filter_by(
            phone=form.user_phone.data).first()
        if query_user_by_phone:
            # 返回注册界面,重新注册
            flash("手机号已被注册!", category="err"
                  )  # Flashes a message to the next request 闪现一条消息到下一次消息请求
            return render_template("user_regist.html", form=form)

        # print("form", form.user_name.data)
        # print("form", form.data)
        # print("form", form.data["user_name"])
        # print("request.form", request.form)
        user = User()
        # user.name = request.form["user_name"]
        user.name = form.user_name.data
        # user.pwd = request.form["user_pwd"]
        user.pwd = generate_password_hash(form.user_pwd.data)
        # user.age = request.form["user_age"]
        user.phone = form.user_phone.data
        # user.birthday = request.form["user_birthday"]
        user.jianjie = form.user_jianjie.data
        # user.email = request.form["user_email"]
        user.email = form.user_email.data
        # user.face = request.form["user_face"]
        # user.face = form.user_face.data
        # filerstorage = form.user_face.data
        user.uuid = str(uuid.uuid4().hex)[0:10]  # 10个字符长度
        filerstorage = request.files["user_face"]  # 获取头像文件
        user.face = secure_filename_with_uuid(
            filerstorage.filename
        )  # secure_filename 文件名安全性检测,如果文件名有特殊字符,会将特殊字符转义,没有就返回原文件名
        # print(user.face)

        # 保存用户头像文件
        # user_folder = os.path.join(app.config["UPLOADS_FOLDER"], user.name)
        # create_folder(user_folder)  # 创建用户文件夹
        # filerstorage.save(os.path.join(user_folder, user.face))
        try:
            photosSet.save(storage=filerstorage,
                           folder=user.name,
                           name=user.face)
            # 如果不存在执行插入操作,创建一个用户类 User 的实例
            # 插入一条数据
            db.session.add(user)
            db.session.commit()
            flash("注册成功!", category="ok")
            # username作为查询参数带到url中去
            # 重定向页面 生成url 执行 user_login 函数 跳转到登录界面
            return redirect(url_for("user_login", username=user.name))
        except UploadNotAllowed:
            flash("头像文件格式错误!", category="err")
            return render_template("user_regist.html", form=form)

    return render_template("user_regist.html", form=form)
コード例 #18
0
def user_info():  # 修改个人信息
    user = User.query.get_or_404(int(session.get('user_id')))  # 如果查找不到就抛出404错误

    # 打开修改信息页面,将原来信息展示出来,消息回填

    form = InfoForm()
    if request.method == "GET":
        form.user_jianjie.data = user.jianjie
    if form.validate_on_submit():
        current_login_name = session.get("user_name")

        old_name = user.name
        new_name = request.form["user_name"]
        query_user_by_name = User.query.filter_by(name=new_name).first()
        query_user_by_phone = User.query.filter_by(
            phone=request.form["user_phone"]).first()
        query_user_by_email = User.query.filter_by(
            email=request.form["user_email"]).first()
        print()

        if query_user_by_phone != None and user.phone != query_user_by_phone.phone:
            flash(message="手机号已被注册!", category="err")
            print(1111)
            return render_template("user_info.html", user=user, form=form)
        elif query_user_by_email != None and user.email != query_user_by_email.email:
            flash(message="邮箱已被注册!", category="err")
            print(222)
            return render_template("user_info.html", user=user, form=form)
        elif query_user_by_name != None and current_login_name != query_user_by_name.name:  # 如果数据库没有这个用户名或者当前登录的用户名和更改的用户名一样(本人操作),都可以更新个人信息
            flash(message="用户名已存在!", category="err")
            print(333)
            return render_template("user_info.html", user=user, form=form)
        else:
            user.name = request.form["user_name"]
            user.email = request.form["user_email"]
            user.phone = request.form["user_phone"]
            user.jianjie = request.form["user_jianjie"]
            filestorage = request.files["user_face"]  # 获取头像文件
            # filestorage = form.user_face.data  # 获取头像文件
            if filestorage.filename != "":
                # # 检查用户上传的头像文件名是否符合要求
                # if not check_files_extension([form.user_face.data.filename], ALLOWED_IMAGEEXTENSIONS):
                #     flash("头像文件格式错误!", category="err")
                #     return redirect(url_for("user_info"))
                # 若果上传了新的头像文件,首先删除旧的,再保存新的
                # user_folder = os.path.join(app.config["UPLOADS_FOLDER"], old_name)
                # 删除就旧的头像
                # os.remove(path=os.path.join(user_folder, user.face))
                # 获取旧头像的存储路径
                userface_path = photosSet.path(filename=user.face,
                                               folder=old_name)
                # 删除就旧的头像
                os.remove(userface_path)

                # 保存新的
                user.face = secure_filename_with_uuid(filestorage.filename)
                # filestorage.save(os.path.join(user_folder, user.face))
                photosSet.save(storage=filestorage,
                               folder=old_name,
                               name=user.face)
                pass
            # 判断是否修改了用户名:如果修改了则同时修改用户上传资源文件夹
            if old_name != new_name:
                os.rename(os.path.join(app.config["UPLOADS_FOLDER"], old_name),
                          os.path.join(app.config["UPLOADS_FOLDER"], new_name))
                pass

            # update_user_by_name(old_name, user)
            db.session.add(user)  # 当插入数据时,检测到插入的数据主键(id) 已存在 则更新原数据
            db.session.commit()
            flash(message="用户信息已更新!", category="ok")
            session["user_name"] = user.name
            session["user_id"] = user.id
            return redirect(url_for("user_detail"))
    return render_template("user_info.html", user=user, form=form)
コード例 #19
0
def album_upload():  # 相册首页
    form = AlbumUploadForm()
    albums = Album.query.filter_by(
        user_id=session["user_id"]).all()  # 获取全部相册标签
    # 动态构造form表单数据: 相册的id作为form.album_title.data即 form.album_title.data为当前相册的id
    form.album_title.choices = [(item.id, item.title)
                                for item in albums]  # 获取到数据库中存储的全部相册标签然后动态填写

    if len(albums) < 1:
        flash(message="请先创建一个相册,再上传照片!", category="err")
        return redirect(url_for("album_create"))

    if request.method == "POST":
        fses = request.files.getlist("album_upload")  # 获取上传的多个文件
        # 检查文件扩展名,将合格的文件过滤出来
        valid_fses = check_filestorages_extension(
            fses, allowed_extensions=ALLOWED_IMAGEEXTENSIONS)
        if len(valid_fses) < 1:
            flash(message="只允许上传文件类型:" + str(ALLOWED_IMAGEEXTENSIONS),
                  category="err")
            return redirect(url_for("album_upload"))
        else:
            # 获取当前相册的名称
            files_url = []
            album_title = ""
            for id, title in form.album_title.choices:
                if id == form.album_title.data:
                    album_title = title
            # 开始遍历保存每一个合格文件
            for fs in valid_fses:
                name_origin = secure_filename_with_uuid(fs.filename)
                folder = session.get("user_name") + "/" + album_title
                fname = photosSet.save(fs, folder=folder, name=name_origin)
                ts_path = photosSet.config.destination + "/" + folder
                # 创建并保存缩略图  photosSet.config.destination=app.config['UPLOADED_PHOTOS_DEST']   绝对路径 uploads文件夹
                name_thumb = create_thumbnail(path=ts_path,
                                              filename=name_origin,
                                              base_width=300)
                # 获取保存缩略图文件的url
                # furl = photosSet.url(fname)  #原图url
                furl = photosSet.url(folder + "/" + name_thumb)
                files_url.append(furl)
                # 创建并保存大图
                name_show = create_show(path=ts_path,
                                        filename=name_origin,
                                        base_width=800)

                # 将产生的Photo对象保存到数据库中去
                photo = Photo(origname=name_origin,
                              showname=name_show,
                              thumbname=name_thumb,
                              album_id=form.album_title.data)
                # 更新数据库
                db.session.add(photo)
                db.session.commit()

                furl = photosSet.url(folder + "/" + name_thumb)
                # files_url.append(furl)

            # 当前上传图片的相册
            print("当前相册id: ", form.album_title.data)
            # 获取当前相册 form构造的时候 相册的id作为form.album_title.data即 form.album_title.data为当前相册的id
            album = Album.query.filter_by(id=form.album_title.data).first()
            album.photonum += len(valid_fses)
            # 更新数据库
            db.session.add(album)
            db.session.commit()
            message = "成功上传 " + str(
                len(valid_fses)) + " 张图片!!" + "当前相册共有 " + str(
                    album.photonum) + " 张图片!!"
            flash(message=message, category="ok")

            return render_template("album_upload.html",
                                   form=form,
                                   files_url=files_url)

    return render_template("album_upload.html", form=form)