Integrate xhEditor text editor into Python's Flask site

高洛峰
Release: 2017-03-03 13:37:06
Original
1395 people have browsed it

Introduction to xhEditor

xhEditor is a simple, mini and efficient visual HTML editor developed based on jQuery. It is based on network access and is compatible with IE 6.0+, Firefox 3.0+, Opera 9.6+, Chrome 1.0+, Safari 3.22+.

xhEditor used to be my favorite editor, and it was also one of the first editors to support drag-and-drop uploading. xhEditor was an excellent editor back then, with powerful enough functions and a pretty good user experience. Drag-and-drop uploading was my favorite feature, but it’s a pity that development has stopped. The last stable version of xhEditor is 1.1.14, which has not been updated for more than 2 years (the development version 1.2.1 was released in 2013). The author has stopped development and maintenance, and the community forum cannot be opened at all.

Since xhEditor is developed based on jQuery, it does not support new versions of jQuery very well. Only version 1.4 of jQuery is the best supported.

Although it is no longer updated, she is still fully capable in some situations where a rich text editor is needed.

This article takes version 1.1.14 as an example to describe how to use the xhEditor editor in the Flask project and implement the back-end functions of image upload and file upload.

xhEditor main features:

  • Simplified Mini: Initial load of 4 files, including: 1 js (50k) + 2 css (10k) + 1 image (5k), a total of 65k. If js and css files are compressed and transmitted using gzip, they can be further reduced to about 24k.

  • Easy to use: A simple calling method and adding a class attribute can instantly turn your textarea into a feature-rich visual editor.

  • Accessibility: Provides comprehensive support for WAI-ARIA, full keyboard for fine operation, and full voice guidance, providing a perfect barrier-free access experience, allowing people with disabilities to write a wonderful life.

  • Built-in Ajax upload: Built-in powerful Ajax upload, including HTML4 and HTML5 upload support (multiple file uploads, real upload progress and file drag-and-drop upload), clipboard upload and remote capture Take upload and pursue the perfect user upload experience.

  • Word automatic cleaning: realizes automatic detection and cleaning of Word code, provides an efficient and perfect Word code filtering solution, and generates code that is optimized and streamlined without losing any details.

  • UBB Visual Editing: Provides a perfect UBB visual editing solution. While you obtain safe and efficient code storage, you can also enjoy the convenience of visual editing.

Using xhEditor in the Flask project
First we need to download the 1.1.14 version of the xhEditor editor from the xhEditor official website, and then unzip it to
The static/xheditor directory of the Flask project.

Integrate xhEditor text editor into Pythons Flask site

Integrate xhEditor text editor into Pythons Flask site

xhEditor provides 2 initialization methods: Class initialization and JavaScript initialization. Class initialization only requires setting the class attribute of xheditor to the textarea, and it will automatically become the xhEditor editor. A page can be in multiple editors at the same time, and parameters can be added to this class attribute. (PS: CKEditor also has this function)

For these two initialization methods, the official website provides a very convenient setup wizard, making the configuration relatively simple.

Sample code:

<head>
<script type="text/javascript" charset="utf-8" src="{{ url_for(&#39;static&#39;, filename=&#39;xheditor/jquery/jquery-1.4.4.min.js&#39;) }}"></script>
<script type="text/javascript" charset="utf-8" src="{{ url_for(&#39;static&#39;, filename=&#39;xheditor/xheditor-1.1.14-zh-cn.min.js&#39;) }}"></script>
<style>.xheditor {width: 640px; height:320px;}</style>
</head>

<body>
<textarea id="content" name="content" class="xheditor {tools:&#39;mfull&#39;}"></textarea>
</body>
Copy after login

Now, we have an xhEditor editor.

Integrate xhEditor text editor into Pythons Flask site

Enable the upload function
xhEditor’s upload function requires setting several parameters (take image upload as an example):

  • upImgUrl: Image file upload receiving URL, for example: /upload/, you can use the built-in variable {editorRoot}

  • upImgExt: Restrict local files before image uploading Extension, default: jpg, jpeg, gif, png

Assuming that the uploaded file receiving URL is /upload/, our editor initialization code becomes:

<textarea class="xheditor {tools:&#39;mfull&#39;,upImgUrl:&#39;/upload/&#39;}"></textarea>
Copy after login

Other types of file upload settings are analogous.

Flask handles upload requests
xhEditor supports 2 upload methods: standard HTML4 upload and HTML5 upload.

  • HTML4 upload uses the standard form upload field. The name of the upload file field is: filedata

  • The entire POST data stream uploaded by HTML5 is uploaded The complete data of the file, and the local file name and other information are stored in the server variable HTTP_CONTENT_DISPOSITION.

  • The returned content must be a standard json string, and the structure can be As follows:

{"err":"","msg":"200906030521128703.gif"} 或者
{"err":"","msg":{"url":"200906030521128703.jpg","localfile":"test.jpg","id":"1"}}
Copy after login

Note: If you select structure 2, the url variable is required.

文件上传处理示例代码:

def gen_rnd_filename():
  filename_prefix = datetime.datetime.now().strftime(&#39;%Y%m%d%H%M%S&#39;)
  return &#39;%s%s&#39; % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route(&#39;/upload/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def upload():
  &#39;&#39;&#39;文件上传函数

  本函数未做上传类型判断及上传大小判断。
  &#39;&#39;&#39;
  result = {"err": "", "msg": {"url": "", "localfile": ""}}

  if request.method == &#39;POST&#39; and &#39;filedata&#39; in request.files:
    # 传统上传模式,IE浏览器使用这种模式
    fileobj = request.files[&#39;filedata&#39;]
    fname, fext = os.path.splitext(fileobj.filename)
    rnd_name = &#39;%s%s&#39; % (gen_rnd_filename(), fext)
    fileobj.save(os.path.join(app.static_folder, &#39;upload&#39;, rnd_name))
    result["msg"]["localfile"] = fileobj.filename
    result["msg"]["url"] = &#39;!%s&#39; % \
      url_for(&#39;static&#39;, filename=&#39;%s/%s&#39; % (&#39;upload&#39;, rnd_name))

  elif &#39;CONTENT_DISPOSITION&#39; in request.headers:
    # HTML5上传模式,FIREFOX等默认使用此模式
    pattern = re.compile(r"""\s.*?\s?filename\s*=\s*[&#39;|"]?([^\s&#39;"]+).*?""", re.I)
    _d = request.headers.get(&#39;CONTENT_DISPOSITION&#39;).encode(&#39;utf-8&#39;)
    if urllib.quote(_d).count(&#39;%25&#39;) > 0:
      _d = urllib.unquote(_d)
    filenames = pattern.findall(_d)
    if len(filenames) == 1:
      result["msg"]["localfile"] = urllib.unquote(filenames[0])
      fname, fext = os.path.splitext(filenames[0])
    img = request.data
    rnd_name = &#39;%s%s&#39; % (gen_rnd_filename(), fext)
    with open(os.path.join(app.static_folder, &#39;upload&#39;, rnd_name), &#39;wb&#39;) as fp:
      fp.write(img)

    result["msg"]["url"] = &#39;!%s&#39; % \
      url_for(&#39;static&#39;, filename=&#39;%s/%s&#39; % (&#39;upload&#39;, rnd_name))

  return json.dumps(result)
Copy after login

远程抓图
一般情况下,当复制站外的图片时,我们希望可以把图片保存到本地,远程抓图就可以完成这个事情。

启用远程抓图功能,需要设置2个参数:

  • localUrlTest : 非本站域名测试正则表达式

  • remoteImgSaveUrl : 远程图片抓取接收程序URL

设置这2个参数之后,我们的编辑器初始化代码变成:


复制代码 代码如下:




这里表示抓取除localhost之外其它域名的图片。

远程抓图处理示例代码:

def gen_rnd_filename():
  filename_prefix = datetime.datetime.now().strftime(&#39;%Y%m%d%H%M%S&#39;)
  return &#39;%s%s&#39; % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route(&#39;/uploadremote/&#39;, methods=[&#39;POST&#39;])
def uploadremote():
  """
  xheditor保存远程图片简单实现
  URL用"|"分隔,返回的字符串也是用"|"分隔
  返回格式是字符串,不是JSON格式
  """
  localdomain_re = re.compile(r&#39;https?:\/\/[^\/]*?(localhost:?\d*)\/&#39;, re.I)
  imageTypes = {&#39;gif&#39;: &#39;.gif&#39;, &#39;jpeg&#39;: &#39;.jpg&#39;, &#39;jpg&#39;: &#39;.jpg&#39;, &#39;png&#39;: &#39;.png&#39;}
  urlout = []
  result = &#39;&#39;
  srcUrl = request.form.get(&#39;urls&#39;)
  if srcUrl:
    urls = srcUrl.split(&#39;|&#39;)
    for url in urls:
      if not localdomain_re.search(url.strip()):
        downfile = urllib.urlopen(url)
        fext = imageTypes[downfile.headers.getsubtype().lower()]
        rnd_name = &#39;%s%s&#39; % (gen_rnd_filename(), fext)
        with open(os.path.join(app.static_folder, &#39;upload&#39;, rnd_name), &#39;wb&#39;) as fp:
          fp.write(downfile.read())
        urlreturn = url_for(&#39;static&#39;, filename=&#39;%s/%s&#39; % (&#39;upload&#39;, rnd_name))
        urlout.append(urlreturn)
      else:
        urlout.append(url)
  result = &#39;|&#39;.join(urlout)
  return result
Copy after login


更多Integrate xhEditor text editor into Pythons Flask site相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template