I have a function in views.py accepting petitions that get some text and a book pk and save the text to a fragments table and update the book text with the new fragment.
The fragments are saved correctly, but the book doesn't. I get the response, but it doesn't save to the database when I manually check it.
This is my code:
profilelogged = validtoken(request.META['HTTP_MYAUTH'])
if not profilelogged:
return HttpResponse('Unauthorized', status=401)
else:
index = request.GET.get('id', 0)
petitiontext = request.GET.get('texto', '')
petitiontext = petitiontext.strip()
todaynoformat = datetime.now()
bookselected = Books.objects.filter(pk=index).first()
actualwait = Waits.objects.filter(book=bookselected).order_by('ordernum').first()
if not actualwait:
response = 'MAL: No hay nadie en espera'
else:
profilewaiting = actualwait.profile
if profilewaiting.pk == profilelogged.pk and actualwait.writting == 1:
newfragment = Fragments(profile=profilelogged, book=bookselected, date=todaynoformat.isoformat(), texto=petitiontext)
newfragment.save()
newtextfull = bookselected.text+" "+petitiontext
bookselected.text = newtextfull
bookselected.save()
actualwait.writting = 2
actualwait.save()
response = bookselected.text
else:
response = 'MAL: No eres el siguiente en la lista o no estas activado para escribir'
return HttpResponse(response)
Forget about the waiting thing, its some waitlist i used to check if the user is able to submit fragments or not and thats working good.
Any thoughts on why book is not saving to DB? I'm using this object.save() method in other functions and its working, but here it doesn't.
Thanks.
Ok, my bad.
I was trying to update same object on two different functions. So I had to figure out how to update it on one unique function and that's the solution.
Thanks anyway.
Related
Sorry if this is a dumb question, I'm a very noob coder.
I'm trying to itinerate through a folder and create DataFrames for each file (then saving it).
Thing is, I changed nothing from when it was not in a for loop (for testing) and it was working perfectly fine, but now in the for loop it yields an empty DataFrame, so I can't do anything.
The important (failure) part of the code is as follows:
filePath=(insert pathFile here)
def CDPBot():
fileItineration = filePath + '/' + files
file = pd.read_excel(fileItineration)
# Agarra el nombre de la empresa para despues
companyName= str(file['Final Account Name'][2])
#companyName=file.loc[3:2]
#companyName=companyName.columns.values[2]
#DMU
faID=os.path.basename(files)
faID=faID[-0:-5]
#Arma el DF usando los filtros proporcionados
f_file = file.loc[(f_file['Segment'] == ('SMB')) & (f_file['Final Account ID'] == faID) | (f_file['Segment'] == ('Commercial')) & (f_file['Final Account ID'] == faID)]
if file.empty:
print('file is empty!')
elif f_file.empty:
print('f_file is empty')
...
...
...
for files in os.listdir(filePath):
CDPBot()
Issue is f_file is an empty DataFrame no matter what I do or try. I don't know why it's yielding that result, any ideas? The rest of the code (I didn't paste everything because it's irrelevant) works just fine.
Thanks in advance!
I am new to python and currently learning this language. I am trying to build a web scraper that will export the data to a CSV. I have the data I want and downloaded it to a CSV. The problem is that I have only managed to dump the data from one index and I want to dump all the data from all the indexes into the same CSV to form a database.
The problem I have is that I can only request n_companies indicating the index. For example (n_company[0] ) and I get the data from the first index of the list. What I want is to get all the data from all the indexes in the same function and then dump them with pandas in a CSV and thus be able to create a DB.
I'm stuck at this point and don't know how to proceed. Can you help me please.
This is the function:
def datos_directorio(n_empresa):
r = session.get(n_empresa[0])
home=r.content.decode('UTF-8')
tree=html.fromstring(home)
descripcion_direccion_empresas = '//p[#class = "paragraph"][2]//text()[normalize-space()]'
nombre_e = '//h1[#class ="mb3 h0 bold"][normalize-space()]/text()'
email = '//div[#class = "inline-block mb1 mr1"][3]/a[#class = "mail button button-inverted h4"]/text()[normalize-space()]'
teléfono = '//div[#class = "inline-block mb1 mr1"][2]/a[#class = "tel button button-inverted h4"]/text()[normalize-space()]'
d_empresas=tree.xpath(descripcion_direccion_empresas)
d_empresas = " ".join(d_empresas)
empresas_n=tree.xpath(nombre_e)
empresas_n = " ".join(empresas_n[0].split())
email_e=tree.xpath(email)
email_e = " ".join(email_e[0].split())
teléfono_e=tree.xpath(teléfono)
teléfono_e = " ".join(teléfono_e[0].split())
contenido = {
'EMPRESA' : empresas_n,
'EMAIL' : email_e,
'TELÉFONO' : teléfono_e,
'CONTACTO Y DIRECCIÓN' : d_empresas
}
return contenido
Best regards.
This is the thing, I was trying to make a crud for a rest api for a movie app, I was able to successfully perform the functionalities with flask to create a movie within the json, to delete a movie, and to list them, but I have problems with being able to edit one of the movies inside the JSON since I don't know how to access a sector of it to be able to modify it, this is what I was trying:
def __init__(self, idpelicula, nombre, descripcion, elenco, restriccionedad, fecha, calificacion):
self.idpelicula = idpelicula
self.nombre = nombre
self.descripcion = descripcion
self.elenco = elenco
self.restriccionedad = restriccionedad
self.fecha = fecha
self.calificacion = calificacion
movies_list = [
Peliculas(1, "Shrek", "Pelicula de Ogro", "Shrek, Fiona", "+APTA", "2001", "10"),
Peliculas(2, "Shrek2", "Otra Pelicula de Ogro", "Shrek, Fiona", "+APTA", "2005", "10"),
]
#app.route("/movies")
def list_movies():
return jsonify([pelicula.__dict__ for pelicula in movies_list])
#app.route("/movies/<id_search_movie>")
def obtener_pelicula(id_search_movie):
for pelicula in movies_list:
if pelicula.idpelicula == int(id_search_movie):
return jsonify(pelicula.__dict__)
return "Pelicula no encontrada", 404
#app.route("/movies", methods=['POST'])
def create_movie():
movie_data = request.get_json()
new_movie = Peliculas(movie_data["idpelicula"], movie_data["nombre"], movie_data["descripcion"],
movie_data["elenco"], movie_data["restriccionedad"], movie_data["fecha"],
movie_data["calificacion"])
movies_list.append(new_movie)
return "OK", 200
#app.route("/movies/<id_delete_movie>", methods=['DELETE'])
def delete_movie(id_delete_movie):
for pelicula in movies_list:
if pelicula.idpelicula == int(id_delete_movie):
movies_list.remove(pelicula)
return "OK", 200
This is what I dont know how to do, (I know its wrong, and that this isn't even the logic to do this), but this is what I tried:
#app.route("/movies", methods=['PUT'])
def edit_movie():
movie_data = request.get_json()
new_movie = Peliculas(movie_data["idpelicula"], movie_data["nombre"], movie_data["descripcion"],
movie_data["elenco"], movie_data["restriccionedad"], movie_data["fecha"],
movie_data["calificacion"])
movies_list.append(new_movie)
return "OK", 200
Any help, even from the point of view of the logic behind doing this will come handy. Thanks to you all.
There is a ton of problems with the way you are coding this at the moment, but here i will show you how you can edit an object in the way you are currently doing it.
So with your approach the edit view should be like this:
#app.route("/movies", methods=['PUT'])
def edit_movie():
# Accessing data from request
movie_data = request.get_json()
# Accesing Object from the movie-list by ID
for movie in movies_list:
if movie.idpelicula == movie_data["idpelicula"]:
edited_movie = movie
# Modifying the object attributes
for name, value in movie_data.items():
if hasattr(edited_movie, name):
setattr(edited_movie, name, value)
return "OK", 200
The problem here is that you were creating a new instance instead of editing an existing one.
in the future you could explore the usage of SQLAlchemy models so you can persist the data in a database, and still be managing objects.
PD1: Finally i recommend you be coherent with the naming, by this i mean if you are calling your variables and classes in spanish Pelicula, peliculas, try to use the same naming throught all your code, same if you use english.
PD2: Study some basic python usage of classes and variable assignment, so you can improve your code.
Greetings from Chile.
I am currently trying to change the name of the "Delete Selected" admin action. I have already effectively override the default (so I can store some data before completely deleting it), but now I want to change the option from the vague "Deleted selected" to something more specific like "Deleted all selected registrations." Or, at least, for it to say, "Deleted selected registrations" like it did before I overwrote the function.
I have so far tried this:
delete_selected.short_description = 'Delete all selected registrations'
But the option is still "Deleted selected." Is there a way to fix this?
Here's my code:
def delete_selected(modeladmin, request, queryset):
"""
This overrides the defult deleted_selected because we want to gather the data from the registration and create a
DeletedRegistration object before we delete it.
"""
for registration in queryset:
reg = registration.get_registrant()
if registration.payment_delegation:
delegate_name = registration.payment_delegation.name
delegate_email = registration.payment_delegation.email
else:
delegate_name = None
delegate_email = None
registration_to_delete = DeletedRegistration.objects.create(
registrant_name = reg.full_name(),
registrant_email = reg.email,
registrant_phone_num = reg.phone,
delegate_name = delegate_name,
delegate_email = delegate_email,
# Filtering out people (with True) who couldn't participate in events because we are only interested in the people
# we had to reserve space and prepare materials for.
num_of_participants = registration.get_num_party_members(True),
special_event = registration.sibs_event,
)
registration.delete()
delete_selected.short_description = 'Delete all selected registrations'
edit: just tried delete_selected.list_display that didn't work either
You can't have it in the function, so I just had to tab it back one space and it worked.
example:
def delete_selected(modeladmin, request, queryset)
code
delete_selected.short_description = "preferred name"
thanks.
I have at the moment to figure out where "favicon.ico" comes from. It is really super weird.
I use geopy to geocode a location into latitude and longitude, then I use these values to create markers on a google map (Flask GoogleMaps).
That is the piece of code:
try:
print findroomcity
location = geolocator.geocode(findroomcity)
print location, location.latitude, location.longitude
if location:
mymap = Map(
identifier="view-side",
lat=location.latitude,
lng=location.longitude,
markers=[(location.latitude, location.longitude)],
zoom = 12
)
else:
print "location is none"
In this case findroomcity is "dortmund". It is actually grabbed from a form.
If I submit the form the map is actually created, so it does not use the else block But it tells me that location in NoneType and has no attribute latitude. It seems that it calls the try block three times and the first time findroomcity is "favicon.ico", also the last time
Check the outputs of the prints:
I dont even used "favicon.ico" in my whole project, I know it must be somewhere but I checked every .py file and also searched for every print. I am really super confused, I keep searching, but maybe someone has encountered something similar.
Here is the whole method which creates the map:
# Die Filter Funktion mit Google Maps
#app.route('/<findroomcity>', methods=["GET", "POST"])
def find_room(findroomcity):
form = FilterZimmerForm()
if form.validate_on_submit():
query = Zimmer.query
filter_list = ["haustiere_erlaubt","bettwaesche_wird_gestellt","grill_vorhanden","safe_vorhanden","kuehlschrank_vorhanden","rauchen_erlaubt","parkplatz_vorhanden",
"kochmoeglichkeit_vorhanden","restaurant_im_haus_vorhanden","handtuecher_werden_gestellt","tv_vorhanden","waschmoeglichkeit_vorhanden","wlan_vorhanden"]
for filter_name in filter_list:
if getattr(form, filter_name).data:
query = query.filter(getattr(Zimmer, filter_name).is_(True))
all_rooms_in_city = query.all()
else:
all_rooms_in_city = Zimmer.query.order_by(desc("stadt")).all()
try:
print findroomcity
location = geolocator.geocode(findroomcity)
print location, location.latitude, location.longitude
if location:
mymap = Map(
identifier="view-side",
lat=location.latitude,
lng=location.longitude,
markers=[(location.latitude, location.longitude)],
zoom = 12
)
else:
print "location is none"
except AttributeError as e:
flash("Ort nicht gefunden")
print e
return redirect(url_for('index'))
except GeocoderTimedOut as e:
print e
sleep(1)
return render_template('zimmer_gefunden.html', mymap=mymap, all_rooms_in_city=all_rooms_in_city, findroomcity=findroomcity, form=form)
EDIT
I have really no idea where it comes from, I use now:
if location.latitude is not None: