简体   繁体   English

在Django中执行外部脚本的推荐做法是什么?

[英]What is the recommended practice in django to execute external scripts?

I'm planning to build a WebApp that will need to execute scripts based on the argument that an user will provide in a text-field or in the Url. 我打算构建一个WebApp,它将需要根据用户将在文本字段或Url中提供的参数来执行脚本。

possible solutions that I have found: 我发现的可能解决方案:

  1. create a lib directory in the root directory of the project, and put the scripts there, and import it from views. 在项目的根目录中创建一个lib目录,并将脚本放在此处,然后从视图导入它。

  2. using subprocess module to directly run the scripts in the following way: 使用子流程模块通过以下方式直接运行脚本:

     subprocess.call(['python', 'somescript.py', argument_1,...]) 

argument_1: should be what an end user provides. arguments_1:应该是最终用户提供的内容。

I'm planning to build a WebApp that will need to execute scripts 我打算构建一个需要执行脚本的WebApp

Why should it "execute scripts" ? 为什么要“执行脚本”? Turn your "scripts" into proper modules , import the relevant functions and call them. 将您的“脚本”转换为适当的模块 ,导入相关功能并进行调用。 The fact that Python can be used as a "scripting language" doesn't mean it's not a proper programming language. Python 可以用作“脚本语言”的事实并不意味着它不是适当的编程语言。

Approach (1) should be the default approach. 方法(1)应该是默认方法。 Never subprocess unless you absolutely have to. 除非绝对必要,否则请勿进行子处理。

Disadvantages of subprocessing: 子处理的缺点:

  1. Depends on the underlying OS and in your case Python (ie is python command the same as the Python that runs the original script?). 取决于底层操作系统以及您所用的Python(即python命令与运行原始脚本的Python是否相同?)。
  2. Potentially harder to make safe. 可能更难保证安全。
  3. Harder to pass values, return results and report errors. 难以传递值,返回结果和报告错误。
  4. Eats more memory and cpu (a side effect is that you can utilize all cpu cores but since you are writing a web app it is likely you do that anyway). 占用更多的内存和cpu(副作用是您可以利用所有cpu内核,但是由于您正在编写Web应用程序,因此无论如何都可能这样做)。
  5. Generally harder to code and maintain. 通常更难编码和维护。

Advantages of subprocessing: 子处理的优点:

  1. Isolates the runtime. 隔离运行时。 This is useful if for example scripts are uploaded by users. 例如,如果脚本是由用户上传的,则这很有用。 You don't want them to mess with your application. 您不希望他们弄乱您的应用程序。
  2. Related to 1: potentially easier to dynamically add scripts. 与1相关:可能更容易动态添加脚本。 Not that you should do that anyway. 并不是说您还是应该这样做。 Also becomes harder when you have more then 1 server and you need to synchronize them. 当您拥有多于1台服务器并且需要同步它们时,也会变得更加困难。
  3. Well, you can run non-python code that way. 好了,您可以通过这种方式运行非python代码。 But it doesn't apply to your case. 但这不适用于您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM