def createUser(custObj): try: print "in" user = None user = User(username=custObj.email, email=custObj.email, first_name=custObj.first_name, last_name=custObj.last_name ) user.set_password(custObj.password) user.save() if user: print "user ok" if hasattr(custObj,'usertype') and custObj.usertype == 'director': print custBll.send(custObj) print "yes" print type(custObj.dob) customer = Customers(user=user,dob=custObj.dob, gender=custObj.gender, usertype=custObj.usertype, ) print customer.userid print "afetre " customer.save() s=findCustomer(custObj) print s.__str__ print "suer" return s except: return False
def create(request): user = users.get_current_user() for i in range(100): createTimeStamp = time.mktime(datetime.now().timetuple()) Customers._insert_customers( randint(1, 3), 'Alex', '123', '0975', '備註...', user, createTimeStamp) return HttpResponse('Done!!!')
def customers_delete(request, id): if request.method == 'DELETE': Customers._delete_customers(int(id)) response_data = {} response_data['result'] = 1 response_data['message'] = 'success' return HttpResponse(json.dumps(response_data), content_type="application/json")
def get(self, id=None): try: if not id: customers = Customers.return_all() return jsonify({'customers': customers}) else: customer = Customers.return_one(id) return jsonify({'customer': serialize(customer)}) except: return {'message': 'Something went wrong'}, 500
def delete(self): data = parserC.parse_args() try: if data['id'] == None: return {'message': 'customer_id field cannot be blank'}, 400 Customers.delete(data['id']) return { 'message': 'customer_id {} was deleted'.format(data['id']) }, 200 except: return {'message': 'Something went wrong'}, 500
def addcustomer(request,new_user): if request.method == "POST": customerform = CustomerForm(request.POST) if customerform.is_valid(): data=customerform.cleaned_data new_user1=User.objects.get(id=new_user) new_user1.groups.add(Group.objects.get(name='customer')) new_customer = Customers(name=data['name'], location=data['location'], user=new_user1) new_customer.save() return HttpResponseRedirect('/homepage') else: customerform = CustomerForm() return render(request, 'printf/addcustomer.html', {'customerform': customerform})
def post(self): data = parserC.parse_args() new_customer = Customers(name=data['name'], dob=data['dob'], updated_at=datetime.now()) try: new_customer.add() return { 'message': 'Customer {} was created'.format(data['name']), 'customer_id': new_customer.id }, 200 except: return {'message': 'Something went wrong'}, 500
def registration(request): success = False if request.method == 'POST': regform = RegForm(request.POST) if regform.is_valid(): fullname = regform.cleaned_data['fullname'] login = regform.cleaned_data['loginid'] pw = regform.cleaned_data['pw'] cfmpw = regform.cleaned_data['cfmpw'] majorccn = regform.cleaned_data['majorccn'] address = regform.cleaned_data['address'] phonenum = regform.cleaned_data['phonenum'] q = Customers.objects.filter(loginid=login); if not q: print('usename avaiable!') if pw!=cfmpw: print('Password mismatch!') elif re.match("^[0-9]{16}|[0-9]{13}$",majorccn) == None: print('Invalid Credit Card No.!') elif re.match("[0-9]+",phonenum) == None: print('Invalid Phone No.!') else: p = Customers(fullname = fullname, loginid = login, pw =pw, majorccn = majorccn, address = address, phonenum = phonenum) p.save() print('account created!') request.session["login"]= True success = True return HttpResponseRedirect('/homepage/') else: print('username taken!') else: regform = RegForm() if "login" in request.session and "loginid" in request.session: login = request.session["login"] loginid = request.session["loginid"] return render(request,'registration.html', {'regform':regform, 'success':success,'login':login,'loginid':loginid}) return render(request,'registration.html', {'regform':regform, 'success':success})
def customers(request): user = users.get_current_user() if request.method == 'GET': user = { 'admin': True if (users.is_current_user_admin() == True) else False, 'userName': user.nickname(), 'logoutUrl': users.create_logout_url('/') } q = query_type = client_type = '' # 查詢值 if 'q' in request.GET: q = request.GET['q'].encode('utf-8').strip() # 查詢條件 if 'query_type' in request.GET: query_type = request.GET['query_type'] # 客戶類型 if 'client_type' in request.GET: client_type = request.GET['client_type'] # 目前頁數 if 'current_page' in request.GET: current_page = int(request.GET['current_page']) else: current_page = 1 # 分頁設定 Customers.page = current_page Customers.limit = 10 params = { 'q': q, 'query_type': query_type, 'client_type': client_type } customers = Customers._get_all_customers(params) # 搜尋結果筆數 total = customers['total'] # 取得分頁 pager = helper_pager(current_page, total, Customers.limit, params) resp_data = { 'user': user, 'customers': customers['result'], 'action': '新增', 'clientType': {1: '政府', 2: '企業', 3: '個人'}, 'pager': pager, 'customers_count': total } return render(request, "customers.html", locals())
def post(self): data = request.get_json() print(f"Data after get_json:{data}") customerDict = customerSchema.load(data) print(f"The customer schema for insert is:{customerDict}") customers = Customers(name=customerDict['name'], lastname=customerDict['lastname'], email=customerDict['email'] ) print(f"The possible dict is:{customers}") customers.save() resp = customerSchema.dump(customers) print(f"Inserting a Customer:{resp}") return resp, 201
def get(self,id): customer = Customers.get_by_id(id) if customer is None: raise ObjectNotFound("Customer not found") resp = customerSchema.dump(customer) print(f"Customer by id: {resp}") return resp
def put(self): try: data = parserC.parse_args() if data['id'] == None: return {'message': 'customer_id field cannot be blank'}, 400 customer = Customers.return_one(data['id']) if data['name'] != None: customer.name = data['name'] if data['dob'] != None: customer.dob = data['dob'] customer.updated_at = datetime.now() Customers.commit() return { 'message': 'Customer {} was updated'.format(data['name']), 'customer_id': data['id'] }, 200 except: return {'message': 'Something went wrong'}, 500
def customers_modify(request, id): user = users.get_current_user() if request.method == 'GET': customer = ndb.Key('Customers', int(id)).get() user = { 'admin': True if (users.is_current_user_admin() == True) else False, 'userName': user.nickname(), 'logoutUrl': users.create_logout_url('/') } resp_data = { 'customer': customer, 'action': '修改', 'clientType': {1: '政府', 2: '企業', 3: '個人'} } return render(request, "customers/customers-data-handle.html", locals()) elif request.method == 'POST': clientName = request.POST['clientName'] type = int(request.POST['type']) clientAddress = request.POST['clientAddress'] clientTel = request.POST['clientTel'] _c = Customers() customer = _c.get_by_id(int(id)) customer.clientName = clientName customer.type = type customer.clientAddress = clientAddress customer.clientTel = clientTel customer.put() resp_data = { 'title': '客戶資料', 'message': '修改成功。 (三秒後自動返回)' } response = render_to_response('success.html', locals()) response['refresh'] = '3;URL=/customers/' return response
def create(self, data): full_name = data['full_name'] email = data['email'] document_type = data['document_type'] document_number = data['document_number'] address = data['address'] customers = Customers(full_name, email, document_type, document_number, address) db.session.add(customers) db.session.commit() return create_customers(customers)
def post(self): """ post: summary: Create a new customer parameters: "first_name": <string> "last_name": <string> "phone_number": <string> "email": <string> "ssn": <string> "active": <bool> responses: 200: Returns JSON object of the customer object created. 400: Bad Request: Most likely a param is missing 500: Internal Server Error """ try: customer = Customers( first_name=request.values['first_name'], last_name=request.values['last_name'], phone_number=request.values['phone_number'], email=request.values['email'], ssn=request.values['ssn'], active=bool(request.values['active']), ) db.session.add(customer) db.session.commit() return jsonify(customer.serialize()) except BadRequestKeyError as e: app.logger.error(str(e)) return {"error": "Bad Request"}, status.HTTP_400_BAD_REQUEST except Exception as e: app.logger.error(str(e)) return {"error": "Internal Server Error"}, status.HTTP_500_INTERNAL_SERVER_ERROR
def delete(self,id): #customer = Customers.simple_filter(id) customer = Customers.get_by_id(id) if customer is None: raise ObjectNotFound("Customer not found") else: customer.delete() resp = customerSchema.dump(customer) print(f"Preparing delete for Customer:{resp}") return resp
def post_customers(payload): response = {} # get and check the user imput body = request.get_json() if body: name = body.get('name') city = body.get('city') adress = body.get('adress') phone = body.get('phone') social_media = body.get('social_media') image_link = body.get('image_link') if name and city and adress and phone and social_media and image_link: customer = Customers(id=None, name=name, city=city, adress=adress, phone=phone, social_media=social_media, image_link=image_link) else: response['success'] = False abort(400) # inser provider data into db if customer: customer.insert() response['success'] = True response['id'] = customer.id response['redirect'] = 'customers' customer.sesion_close() else: abort(400) else: abort(400) # return the response return jsonify(response)
def signup(): form = SignupForm() if request.method == "POST": if form.validate() == False: return render_template('signup.html', form = form) else: newuser = Customers(form.first_name.data, form.last_name.data, form.birthdate, form.email.data, form.password.data) session.add(newuser) session.commit() return "Success!" elif request.method == "GET": return render_template("signup.html", form = form)
def customers_add(request): user = users.get_current_user() if request.method == 'GET': user = { 'admin': True if (users.is_current_user_admin() == True) else False, 'userName': user.nickname(), 'logoutUrl': users.create_logout_url('/') } resp_data = { 'user': user, 'action': '新增', 'clientType': {1: '政府', 2: '企業', 3: '個人'} } return render(request, "customers/customers-data-handle.html", locals()) else: clientName = request.POST['clientName'] type = int(request.POST['type']) clientAddress = request.POST['clientAddress'] clientTel = request.POST['clientTel'] createTimeStamp = time.mktime(datetime.now().timetuple()) Customers._insert_customers( type, clientName, clientAddress, clientTel, '備註...', user, createTimeStamp) resp_data = { 'title': '客戶資料', 'message': '新增成功。 (三秒後自動返回)' } response = render_to_response('success.html', locals()) response['refresh'] = '3;URL=/customers/' return response
def store_user_info(user_phone, user_zip): location = gmaps.get_lat_long(address=user_zip) if location is not None: (lat, lng) = location customer = Customers(phone=user_phone, latitude=lat, longitude=lng, age=18, gender='') print("*** customer object generated:", customer, file=sys.stderr) try: db.session.add(customer) db.session.commit() print("*** Added customer:", str(customer), file=sys.stderr) except exc.IntegrityError: db.session().rollback() print("Potential duplicate entry")
def post(self): customer = Customers(phone=request.json.get('phone', ''), latitude=request.json.get('latitude', ''), longitude=request.json.get('longitude', ''), age=request.json.get('age', 99), gender=request.json.get('gender', ''), family_size=request.json.get('family_size', '')) print("*** customer object generated:", customer, file=sys.stderr) try: db.session.add(customer) db.session.commit() print("*** Added customer:", str(customer), file=sys.stderr) return customer, 201, {'Content-Type': 'application/json'} except exc.IntegrityError: db.session().rollback() return "Potential duplicate entry", 409, { 'Content-Type': 'application/json' }
def send_email(): if request.method == 'POST': email = request.form['email'] customer_check = Customers.query.filter_by(email=email).first() if customer_check: flash('Korisnik vec postoji') return redirect(url_for('index')) customer = Customers(email=email) db.session.add(customer) db.session.commit() token = serializer.dumps(email, salt=ser_key) msg = Message('Potvrda email adrese', recipients=[email]) link = url_for('confirm_email', token=token, _external=True) msg.body = f'Molimo Vas da kliknete na link da bi potvrdili Vasu email adresu, {link}\nLink je validan 24 sata.' mail.send(msg) flash('Molimo Vas provjerite vas email inbox') return redirect(url_for('index'))
def put(self, id): customer = Customers.get_by_id(id) print(f"Customer id to Update is:{id}") if customer is None: raise ObjectNotFound("Customer not found") else: print(f"The original record has:{customer}") name = request.json['name'] lastname = request.json['lastname'] email = request.json['email'] customer.name = name customer.lastname = lastname customer.email = email customer.update() resp = customerSchema.dump(customer) print(f"Updated Customer:{resp}") return resp, 201
def customers(request): action = request.GET.get('action') if action == 'criar': inputNome = request.GET.get('inputNome') if inputNome is not None: inputEmail = request.GET.get('inputEmail') inputTipo = request.GET.get('inputTipo') inputAtivo = request.GET.get('inputAtivo') newCustomer = Customers() newCustomer.name = inputNome newCustomer.email = inputEmail newCustomer.type = inputTipo if inputAtivo is not None: newCustomer.enabled = 'S' else: newCustomer.enabled = 'N' newCustomer.creation_date = datetime.datetime.now() newCustomer.save() CustomersResult = Customers.objects.all() page = request.GET.get('pagina') paginator = Paginator(CustomersResult, 20) #Show 20 per page try: CustomersResult = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. CustomersResult = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. CustomersResult = paginator.page(paginator.num_pages) return render(request, 'SisLocApp/customers.html', {'CustomersResult': CustomersResult, 'action': 'listar', 'status': 'created'}) return render(request, 'SisLocApp/customers.html', {'action': 'criar'}) elif action == 'excluir': inputExcluir = request.GET.get('inputExcluir') CustomerDeleted = Customers.objects.filter(id=inputExcluir) CustomerDeleted.delete() CustomersResult = Customers.objects.all() page = request.GET.get('pagina') paginator = Paginator(CustomersResult, 20) #Show 20 per page try: CustomersResult = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. CustomersResult = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. CustomersResult = paginator.page(paginator.num_pages) return render(request, 'SisLocApp/customers.html', {'CustomersResult': CustomersResult, 'action': 'listar', 'status': 'deleted'}) elif action == 'alterar': inputAlterar = request.GET.get('inputAlterar') CustomersResult = Customers.objects.get(id=inputAlterar) inputNome = request.GET.get('inputNome') if inputNome is None: return render(request, 'SisLocApp/customers.html', {'CustomersResult': CustomersResult, 'action': 'alterar'}) inputEmail = request.GET.get('inputEmail') inputTipo = request.GET.get('inputTipo') inputAtivo = request.GET.get('inputAtivo') CustomersResult.name = inputNome CustomersResult.email = inputEmail CustomersResult.type = inputTipo if inputAtivo == 'on': CustomersResult.enabled = 'S' else: CustomersResult.enabled = 'N' CustomersResult.save() CustomersResult = Customers.objects.all() page = request.GET.get('pagina') paginator = Paginator(CustomersResult, 20) #Show 20 per page try: CustomersResult = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. CustomersResult = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. CustomersResult = paginator.page(paginator.num_pages) return render(request, 'SisLocApp/customers.html', {'CustomersResult': CustomersResult, 'action': 'listar', 'status': 'updated'}) else: CustomersResult = Customers.objects.all() page = request.GET.get('pagina') paginator = Paginator(CustomersResult, 20) #Show 20 per page try: CustomersResult = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. CustomersResult = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. CustomersResult = paginator.page(paginator.num_pages) return render(request, 'SisLocApp/customers.html', {'CustomersResult': CustomersResult, 'action': 'listar'})
def get(self): customers = Customers.get_all() result = customerSchema.dump(customers, many=True) return result
from models import Customers from settings import engine ins = Customers.insert().values(name='Фабрика', inn='23454645') str(ins) conn = engine.connect() result = conn.execute(ins)
python populate.py Author: Tapish Rathore """ import json from app import db from models import Users from models import Customers from models import Transactions with open('users.json') as f: users = json.load(f) Users.query.delete() for u in users["users"]: user = Users() user.user = u["user"] user.key = u["key"] db.session.add(user) db.session.commit() with open('customers.json') as f: customers = json.load(f) Customers.query.delete() for c in customers["customers"]: cust = Customers() cust.name = c["customerName"] cust.amount = c["dueAmount"] cust.duedate = c["dueDate"] cust.mobileno = c["mobileNumber"] db.session.add(cust) db.session.commit() Transactions.query.delete()
def db_start(): create_engine('sqlite:///test.db', convert_unicode=True) db.create_all() db.session.commit() user = User() user.username = "******" user.password = generate_password_hash('admin', method='sha256') user.email = '*****@*****.**' user.admin = True user.poweruser = True db.session.add(user) db.session.commit() #dodanie przykładowych produktów i klientów product1 = Products( name='Car tire A', group='Tires', stock_quantity=1, price=50 ) product2 = Products( name='Car tire B', group='Tires', stock_quantity=3, price=60 ) product3 = Products( name='Car piston A', group='Pistons', stock_quantity=1, price=150 ) customer1 = Customers( name='Kowalex', nip='111-333-222', adress='66-500 Poznan, ul.Niczyja 1', payment=30 ) customer2 = Customers( name='Nowatex', nip='111-444-555', adress='66-500 Poznan, ul.Niczyja 2', payment=21 ) db.session.add(product1) db.session.add(product2) db.session.add(product3) db.session.add(customer1) db.session.add(customer2) db.session.commit() invoice1 = Invoices( customer=customer1 ) invoice2 = Invoices( customer=customer2 ) db.session.add(invoice1) db.session.add(invoice2) db.session.commit() invoice1.invoicing.append(product1) invoice1.invoicing.append(product2) invoice1.invoicing.append(product3) db.session.commit()