search
HomeBackend DevelopmentPython TutorialIntegrate xhEditor text editor into Python's Flask site

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>

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>

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"}}

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)

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

启用远程抓图功能,需要设置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


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

Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 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.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor