Integrate 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.
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('static', filename='xheditor/jquery/jquery-1.4.4.min.js') }}"></script> <script type="text/javascript" charset="utf-8" src="{{ url_for('static', filename='xheditor/xheditor-1.1.14-zh-cn.min.js') }}"></script> <style>.xheditor {width: 640px; height:320px;}</style> </head> <body> <textarea id="content" name="content" class="xheditor {tools:'mfull'}"></textarea> </body>
Now, we have an xhEditor editor.
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:'mfull',upImgUrl:'/upload/'}"></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('%Y%m%d%H%M%S') return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000))) @app.route('/upload/', methods=['GET', 'POST']) def upload(): '''文件上传函数 本函数未做上传类型判断及上传大小判断。 ''' result = {"err": "", "msg": {"url": "", "localfile": ""}} if request.method == 'POST' and 'filedata' in request.files: # 传统上传模式,IE浏览器使用这种模式 fileobj = request.files['filedata'] fname, fext = os.path.splitext(fileobj.filename) rnd_name = '%s%s' % (gen_rnd_filename(), fext) fileobj.save(os.path.join(app.static_folder, 'upload', rnd_name)) result["msg"]["localfile"] = fileobj.filename result["msg"]["url"] = '!%s' % \ url_for('static', filename='%s/%s' % ('upload', rnd_name)) elif 'CONTENT_DISPOSITION' in request.headers: # HTML5上传模式,FIREFOX等默认使用此模式 pattern = re.compile(r"""\s.*?\s?filename\s*=\s*['|"]?([^\s'"]+).*?""", re.I) _d = request.headers.get('CONTENT_DISPOSITION').encode('utf-8') if urllib.quote(_d).count('%25') > 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 = '%s%s' % (gen_rnd_filename(), fext) with open(os.path.join(app.static_folder, 'upload', rnd_name), 'wb') as fp: fp.write(img) result["msg"]["url"] = '!%s' % \ url_for('static', filename='%s/%s' % ('upload', rnd_name)) return json.dumps(result)
远程抓图
一般情况下,当复制站外的图片时,我们希望可以把图片保存到本地,远程抓图就可以完成这个事情。
启用远程抓图功能,需要设置2个参数:
localUrlTest : 非本站域名测试正则表达式
remoteImgSaveUrl : 远程图片抓取接收程序URL
设置这2个参数之后,我们的编辑器初始化代码变成:
复制代码 代码如下:
这里表示抓取除localhost之外其它域名的图片。
远程抓图处理示例代码:
def gen_rnd_filename(): filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S') return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000))) @app.route('/uploadremote/', methods=['POST']) def uploadremote(): """ xheditor保存远程图片简单实现 URL用"|"分隔,返回的字符串也是用"|"分隔 返回格式是字符串,不是JSON格式 """ localdomain_re = re.compile(r'https?:\/\/[^\/]*?(localhost:?\d*)\/', re.I) imageTypes = {'gif': '.gif', 'jpeg': '.jpg', 'jpg': '.jpg', 'png': '.png'} urlout = [] result = '' srcUrl = request.form.get('urls') if srcUrl: urls = srcUrl.split('|') for url in urls: if not localdomain_re.search(url.strip()): downfile = urllib.urlopen(url) fext = imageTypes[downfile.headers.getsubtype().lower()] rnd_name = '%s%s' % (gen_rnd_filename(), fext) with open(os.path.join(app.static_folder, 'upload', rnd_name), 'wb') as fp: fp.write(downfile.read()) urlreturn = url_for('static', filename='%s/%s' % ('upload', rnd_name)) urlout.append(urlreturn) else: urlout.append(url) result = '|'.join(urlout) return result
更多Integrate xhEditor text editor into Pythons Flask site相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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.

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 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.

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 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 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.
