【问题标题】:How can I let users create html files on the file system from a template?如何让用户从模板在文件系统上创建 html 文件?
【发布时间】:2013-02-06 01:48:10
【问题描述】:

现在我的金字塔应用程序的主页有这个可调用的视图,它允许用户向数据库添加新的“页面”。然后可以在单独的 url 上查看这些页面。

@view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
    if 'form.submitted' in request.params:
        name= request.params['name']
        body = request.params['body']

        page=Page(name,data)
        new= DBSession.add(page)
        return HTTPFound(location=request.route_url('view_page',pagename=name))

    return {} 

而不是这个,我希望表单提交在服务器文件系统上创建一个全新的 html 页面。此 html 页面应采用我提供的模板格式,其中包含在提交时从主页表单传递的值。有没有办法做到这一点?我一直在查看http://docs.pylonsproject.org,但找不到方法。

【问题讨论】:

    标签: python database filesystems pyramid


    【解决方案1】:

    我相信您可以使用render 将您的模板/上下文呈现为字符串

    来自this 帖子的示例

    renderer_dict = {} # dictionary of values to pass to the renderer
    new_comment = render('new_comment.pt', renderer_dict, request)
    

    由于您有一个 html 模板,并且您想为您的用户自定义它,您应该能够使用正确的上下文通过 render 运行它并将其保存到您的文件系统中。

    【讨论】:

    • 那是有道理的。一旦我假设的 new_comment 是新的 html 文件被渲染,我将如何将它保存到文件系统并告诉它去哪里?
    • @BigBoy1337 new_comment 是一个字符串,您可以使用 python 文件 api docs.python.org/2/tutorial/inputoutput.html 将其写入文件,基本上有大量示例说明如何使用它f = open('/path/to/file/', 'w'); f.write(new_comment); f.close()
    • 酷。那讲得通。请求值(第二行的最后一部分)在哪里定义?还是我只是把“请求”放在那里?
    • 来自:docs.pylonsproject.org/projects/pyramid/en/latest/api/… 似乎只是传入 request=request 可能会起作用
    猜你喜欢
    • 2022-11-28
    • 2012-02-24
    • 2015-09-23
    • 1970-01-01
    • 2013-08-09
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多