so I'm having trouble getting some data to my DB.
I'm not that good with python and trying to learn.
so this is the data I'm sending to the Django server:
as you can see I'm getting FILES called doc[i] to the server and I want to save the name of the file in the DB.
but I don't know how to loop through it.
that's what I'm doing for now:
def submit_quality_dept_application(request, application_id):
doc0 = request.FILES['doc0']
length = request.data['length']
application = Application.objects.get(id=application_id)
application_state = application.application_state
application_state['doc0'] = doc0.name
Application.objects.filter(id=application_id).update(
application_state=application_state)
return Response(length, status=status.HTTP_200_OK)
that way it's working for doc0 and I can save its name in the DB.
but I want to loop through every doc[i] and save it in DB.
any suggestions?
You can enumerate over the items with a range(…) [Python-doc]:
def submit_quality_dept_application(request, application_id):
n = int(request.data['length'])
application = Application.objects.get(id=application_id)
application_state = application.application_state
for i in range(n):
doc = request.FILES[f'doc{i}']
application_state[f'doc{i}'] = doc.name
Application.objects.filter(id=application_id).update(application_state=application_state)
return Response(length, status=status.HTTP_200_OK)
But I'm not sure if the is the best way to handle multiple files. It might be better to submit a list of files as request, for example for the same key.
Related
So I have SearchResultView(listview) with a method get_context_data were i zip publications and images. For easy looping in the template:
context['publications'] = zip(context['publications'], cover_images)
Now I am testing and I have the following:
def setUp(self):
user = User.objects.create_superuser(username='admin', password='12345', email='')
user.save()
Publication.objects.create(title='eindhoven')
Publication.objects.create(title='لحضور المؤتمر الدولي العاشر ليونيكود')
Publication.objects.create(title='مزامير') #mazamir
And this:
def test_search_results(self):
client = Client('127.0.0.1')
response = client.login(username='admin', password='12345')
response = client.get('/publication/show/', {'q': 'eindhoven'})
Now I need to unpack zip that is in the response.
I tried the following:
list(zip(*response.context['publications']))
list(zip(*response.context[-1]['publications']))
But they are returning an empty list. Anyone any ideas?
So I made an extra context variable for images because I do not have to unpack a zip object. The reason that it returned a empty list was because google translate is not working for search on mazamir (latin to arabic). So it might have worked for zipped objects but it was to much code making it to difficult. So I went with the former solution. In the end i made both zipped object and lists because the template needs zipped object to loop simultaneously.
I'm trying to fetch users list based on their language(from ArrayField). A single user can have multiple languages. When i passed single language{'Hindi'}, it fetches all the records except user with multiple languages, but if passed parameters {'Hindi','bangla','kannada'} then it gives me a specific record,how can i fetch the users list with hindi and other than hindi as well . I have tried with .all also but it didn't worked for me.
Any help would be appreciated.
models.py
# DESCRIPTION: This function gets the drivers list by lang.
#classmethod
def get_driver_by_lang(cls, driver_lang):
try:
driver_details = cls.objects.filter(language = driver_lang)
data = serializers.serialize("json", driver_details)
data = json.loads(data)
return data
except :
return False
How about this:
driver_details = cls.objects.filter(language__contains = driver_lang)
This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 5 years ago.
I'm working on a small web app to create some diagrams and I need to create a variable to hold a unique file name for each web app session so that users don't end up getting the wrong file when they save the diagram as a pdf. To do this I've wrapped the related views in a class using flask_classful and created an instance variable to hold the file name.
class PiperView(FlaskView):
route_base = '/'
def __init__(self):
self.piper_name = '_init_.pdf'
self.tst_index = 0
self.tst_plot = 0
self.tst_download = 0
self.tst_master = 0
#route('/',methods=['GET','POST'])
#route('/index/',methods=['GET','POST'],endpoint='index')
#nocache
def index(self):
self.piper_name = '_piper.pdf'
#test Code
#=======================================================================
file = open(fpath+'index.txt','a')
self.tst_index += 1
self.tst_master += 1
file.write(str(self.tst_index)+"."+str(self.tst_master)+") " +str(self.piper_name)+', ')
file.close()
#=======================================================================
plot_data = np.loadtxt('piper_data.csv', delimiter=',', skiprows=1 )
html_plot = Markup(piper(plot_data, ' ', alphalevel=1.0, color=False, file_nam=self.piper_name))
return render_template('plot.html',title='The Plot', figure=html_plot)
#route('/plot',methods=['GET','POST'],endpoint='plot')
#nocache
def plot(self):
self.piper_name = str(random.randint(0,10000001))+'_piper.pdf'
#test Code
#=======================================================================
file = open(fpath+'plot.txt','a')
self.tst_plot += 1
self.tst_master += 1
file.write(str(self.tst_plot)+"."+str(self.tst_master)+" ) " +str(self.piper_name)+', ')
file.close()
#=======================================================================
try:
f = request.files['data_file']
plot_data = np.loadtxt(f, delimiter=',', skiprows=1 )
html_plot = Markup(piper( plot_data, ' ', alphalevel=1.0, color=False, file_nam=self.piper_name))
return render_template('plot.html',title='The Plot', figure=html_plot)
except:
return render_template('plot.html',title='The Plot', figure="There Seems To Be A Problem With Your Data")
#route('/download',methods=['GET','POST'],endpoint='download')
#nocache
def download(self):
#test Code
#=======================================================================
file = open(fpath+'download.txt','a')
self.tst_download += 1
self.tst_master += 1
file.write(str(self.tst_download)+"."+str(self.tst_master)+") " +str(self.piper_name)+', ')
file.close()
#=======================================================================
return send_from_directory(directory=fpath,filename=self.piper_name)
The problem is that the instance variable that holds the file name doesn't get shared between methods. I added some test code to try and figure out what was happening. The 'tst_index', 'tst_plot' and 'tst_download' each behave as expected in that they get incremented but the 'tst_master' does not get incremented between method calls.
The output from the test code is:
index.txt
1.1) _piper.pdf,
plot.txt
1.1 ) 7930484_piper.pdf, 2.2 ) 9579691_piper.pdf,
download.txt
1.1) init.pdf, 2.2) init.pdf,
when I call the index view one (1) time, the plot view two (2) times and the download view (2) times. As you can see the 'tst_master' instance variable is not getting updated between method calls.
I know this would work in plain python as I tested it but what am I missing about flask and flask_classful that is causing this?
You are overcomplicating your task. You probably don't need to use flask-classful for it.
You can use ordinary flask sessions. Session is unique for each user. The only thing you need is to use some unique ID for each file. This file id can be user id if your users log in into your web app and their credentials are stored in the db. Or you can randomly generate this file id. Then you can store the filename in the flask session like this:
from flask import session
...
def plot(...):
session['user_file_name'] = user_file_name
def download(...):
user_file_name = session['user_file_name']
Hope this helps.
Embedding state like that in your application is generally a bad idea. There is no guarantee that the view instance the generates a response will persist for more than that one request. Store your data outside of flask- server-side on a database, a key-value store, or even a file on disk somewhere, or client-side in the browser. Flask has a number of plugins that make that easier (flask-sqlalchemy, flask-session, flask-redis, etc).
Flask natively offers the flask.session object, which stores information in cookies on the client side. flask-session would probably do what you want without much additional overhead if you were concerned with storing things server side. Just configure it with the File System session interface and you get a flask.session variable that handles all the magic of linking user requests to data stored on the filesystem.
Im new to python and figured that best way to learn is by practice, this is my first project.
So there is this fantasy football website. My goal is to create script which logins to site, automatically creates preselected team and submits it.
I have managed to get to submitting team part.
When I add a team member this data gets sent to server:
https://i.gyazo.com/e7e6f82ca91e19a08d1522b93a55719b.png
When I press save this list this data gets sent:
https://i.gyazo.com/546d49d1f132eabc5e6f659acf7c929e.png
Code:
import requests
with requests.Session() as c:
gameurl = 'here is link where data is sent'
BPL = ['5388', '5596', '5481', '5587',
'5585', '5514', '5099', '5249', '5566', '5501', '5357']
GID = '168'
UDID = '0'
ACT = 'draft'
ACT2 = 'save_draft'
SIGN = '18852c5f48a94bf3ee58057ff5c016af'
# eleven of those with different BPL since 11 players needed:
c.get(gameurl)
game_data = dict(player_id = BPL[0], action = ACT, id = GID)
c.post(gameurl, data = game_data)
# now I need to submit my list of selected players:
game_data_save = dict( action = ACT2, id = GID, user_draft_id = UDID, sign = SIGN)
c.post(gameurl, data = game_data_save)
This code works pretty fine, but the problem is, that 'SIGN' is unique for each individual game and I have no idea how to get this data without using Chromes inspect option.
How can I get this data simply running python code?
Because you said you can find it using devtools I'm assuming SIGN is written somewhere in the DOM.
In that case you can use requests.get().text to get the HTML of the page and parse it with a tool like lxml or HTMLParser
Solved by posting all data without 'SIGN' and in return I got 'SIGN' in html.
I am posting a JSON object back to the server side and retrieving that information through a request. Right now this is my code for my views.py
#csrf_exempt
def save(request):
if request.method == 'POST':
rawdata = request.body
JSONData= json.dumps(rawdata)
return HttpResponse(rawdata)
when I return rawdata my response looks like this:
[{"time_elapsed":"0","volts":"239.3","amps":"19.3","kW":"4.618","kWh":"0","session":"1"},...]
when I return JSONdata my response looks like this:
"[{\"time_elapsed\":\"0\",\"volts\":\"239.1\",\"amps\":\"20.8\",\"kW\":\"4.973\",\"kWh\":\"0\",\"session\":\"1\"},....]
which response is better when trying to insert this data into a sqlite database using Python/Django?
Also how would I start a loop for this do I have to do this kind of code?
conn = sqlite3.connect('sqlite.db')
c = conn.cursor()
c.execute("INSERT STATEMENTS")
I assume I have to do a loop for the INSERT STATEMENTS portion of that code, but I don't have any key to work off of. In my data everything between {} is one row. How do I iterate through this array saying everytime you see {...data...} insert it into a new row?
Here is how I eventually solved my problem. It was a matter of figuring out how to translate the JSON object to something python could recognize and then writing a simple loop to iterate through all the data that was produced.
#csrf_exempt
def save(request):
if request.method == 'POST':
rawdata1 = request.body
rawdata2 = json.loads(rawdata1)
length = len(rawdata2)
for i in range(0,length,1):
x = meterdata(time_elapsed=rawdata2[i]['time_elapsed'], volts=rawdata2[i]['volts'], amps=rawdata2[i]['amps'], kW=rawdata2[i]['kW'], kWh=rawdata2[i]['kWh'], session=rawdata2[i]['session'])
x.save()
return HttpResponse("Success!")
The big differences is the json.loads rather than dumps and in the for loop how to access the newly converted data. The first bracket specifies the row to look in and the second specifies what item to look for. for the longest time I was trying to do data[0][0]. May this help anyone who finds this in the future.
probably if you need to store that data in a db is best to create a model representing it, then you create a ModelForm with associated your model for handling your POST.
In this manner saving the model to the db is trivial and serializing it as a json response is something like
data = serializers.serialize('json',
YourModel.objects.filter(id=id),
fields=('list','of','fields'))
return HttpResponse(data, mimetype='application/json')