我已经为计划使用此第三方应用程序扩展的功能创建了一个单独的应用程序,但我不想触及其代码。
我要扩展的视图,发布问题或获取表格供用户提出问题。我想使用此视图发布文章。它使用的形式是不同的。
伪代码如下:
post_question_view(request)
If user is authenticated and read only, redirect somewhere else.
form = form.Askquestionform(request.REQUEST) ( I would like to do form = form.AskArticleform())
If the request is post and form is valid, get clean data. (The article will include additional data)
If user is authenticated, draft a question and write the question to the database. Generate a new-question-posted signal and redirect. (I don't have to make any changes here I guess)
If user is not authenticated, create anonymous question, write it to the database and redirect to the login page.
If the request is get fill in the form intial and render to ask_question.html (I would like to render to ask_article.html)
大部分代码都需要进行一些细微的改动。我需要填写一些空白,并在现有代码中添加一些新的空白。我如何使用干燥的主干来做到这一点?
我将基于您的伪代码回答这个假设的三个问题,该伪代码post_question_view
是不带参数的老式Django视图(不是基于类的视图):
不,如果两个视图重复代码,则创建一个调用两个视图之一的包装器不是DRY。那只是将重复的代码隐藏在包装器后面。
不,如果没有post_question_view
任何参数来修改其行为(例如使用其他形式),则装饰器将无济于事。
不可以。视图的编写方式不允许进行这些修改。一种情况是它没有参数可以按照您想要的方式更改其行为-如果可以,则可以使用这些参数。另一方面,它不是基于类的视图,其功能被组织为可覆盖的字段和方法-如果是,则可以将视图子类化并覆盖适当的字段和方法。
基于技术性,我所说的话有一个例外。您可以使用Python的inspect
模块在运行时获取代码中原始视图的源代码,然后在运行时按文本级别从字面上修改代码,然后在运行时评估该代码以创建新视图。从技术上讲,这不是DRY,也就是说您不会在源代码中重复自己,但这并不是人们对DRY的意思,因为这是一个可爱的技巧,而不是使用声音代码的组织和体系结构来避免源代码重复。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句