Home Backend Development Python Tutorial Integrate xhEditor text editor into Python's Flask site

Integrate xhEditor text editor into Python's Flask site

Mar 03, 2017 pm 01:37 PM

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中文网!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles