在数据库中保存HTML内容,需要遵循以下步骤:
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(name)
app.config'SQLALCHEMY_DATABASE_URI' = 'sqlite:///pages.db'
db = SQLAlchemy(app)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
content = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, nullable=False)
updated_at = db.Column(db.DateTime, nullable=False)
@app.route('/pages', methods='POST')
def create_page():
data = request.get_json()
page = Page(title=data['title'], content=data['content'], created_at=datetime.now(), updated_at=datetime.now())
db.session.add(page)
db.session.commit()
return {'message': 'Page created successfully'}, 201
@app.route('/pages/<int:page_id>', methods='GET')
def get_page(page_id):
page = Page.query.get(page_id)
if page is None:
return {'message': 'Page not found'}, 404
return {'id': page.id, 'title': page.title, 'content': page.content, 'created_at': page.created_at, 'updated_at': page.updated_at}
注意:在存储HTML内容时,为了确保安全性,需要对用户输入的数据进行验证和过滤,防止跨站脚本攻击(XSS)和其他安全漏洞。可以使用诸如HTMLPurifier之类的库来实现。
领取专属 10元无门槛券
手把手带您无忧上云