我想从django视图调用带有参数的python脚本。 python脚本存储在子文件夹中(参见附图)。
基本上我有一个输入表单,想要使用该表单中的输入数据调用crawl.py。表格数据应存储在变量" production_number"在crawl.py。
view.py
from .forms import CustomerForm, LoginForm
from .models import Orders
from .ERPProgramm.crawl import crawlmain
def newOrders(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
formdata = form.cleaned_data['product_ID']
# call crawl.py with paramter formdata
return HttpResponseRedirect('/customer/newOrders')
crawl.py
import db
import sys
import requests
import json
from datetime import datetime
def query(resource):
r = requests.get('http://11.111.11.11:8080/webapp/api/v1/' + resource,
headers={'AuthenticationToken': '11111-11111-1111-1111-11111'}
)
return r
costumer_id = 1
production_number = formdata
d = query('productionOrder/?productionOrderNumber-eq={}'.format(production_number)).json()
session = db.Session()
costumer = session.query(db.Costumer).get(costumer_id)
if 'result' in d and len(d['result']) > 0:
r = d['result'][0]
order = db.Order()
try:
order.article_id = r['articleId']
order.amount = r['targetQuantity']
order.create_date = datetime.fromtimestamp(r['createdDate'] / 1000)
order.start_date = datetime.fromtimestamp(r['targetStartDate'] / 1000)
order.end_date = datetime.fromtimestamp(r['targetEndDate'] / 1000)
except NameError as e:
sys.exit('Error {}'.format(e.what()))
article_number = r['articleNumber']
d = query('article/?articleNumber-eq={}'.format(article_number)).json()
if 'result' in d and len(d['result']) > 0:
r = d['result'][0]
article_image_id = r['articleImages'][0]['id']
order.price_offer = r['articlePrices'][0]['price']
r = query('article/id/{}/downloadArticleImage?articleImageId={}'.format(order.article_id, article_image_id))
order.article_image = r.content
else:
print('No result for article with number', article_number)
costumer.orders.append(order)
session.add(costumer)
session.commit()
else:
print('No result for production order with article number', article_number)
如何从django视图调用crawl.py?
答案 0 :(得分:0)
settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FILE_DIR = os.path.abspath(os.path.join(BASE_DIR,'/Customer/ERPProgram')
views.py
import sys
sys.path.insert(0, os.path.join(settings.FILE_DIR))
import crawl