key: expected bytes or bytearray, but got 'int' - python-3.x

from flask import Flask, render_template,request,url_for,make_response,redirect,session
from bs4 import BeautifulSoup
import sqlite3
import random
import models
import os
import socket
app = Flask(__name__)
app.config['SECRET_KEY'] = b"HelloWorld"
def check_session():
try:
loggedin = session['loggedin']
except:
session['loggedin'] = False
loggedin = session['loggedin']
return loggedin
#app.route('/')
def index():
loggedin = check_session()
#loggedin = True
blogpost = models.Blogpost()
posts = blogpost.conn.execute("SELECT path FROM posts ORDER BY timestamp DESC")
post_content = []
for post in posts:
post_text = BeautifulSoup(open(post[0],'r').read(),'html.parser')
post_content.append(post_text)
return render_template('home.html',loggedin=loggedin,post_content=post_content)
#return "HelloWorld"
#app.route('/login',methods = ['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html',strike=0)
elif request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = models.User(username)
result = user.authenticate(username,password)
if result == False:
session['loggedin'] = True
session['username'] = username
return render_template(home.html, session['loggedin']
if socket.gethostname() == "DESKTOP-D18" :
if __name__ == '__main__':
app.secret_key=1
app.run(host=os.getenv('IP', '127.0.0.1'),port=int(os.getenv('PORT', 8080)),debug=True)
else :
if __name__ == '__main__':
app.secret_key=1
app.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)),debug=True)
This is my Flask app. When I run it , it gives the following error:
key: expected bytes or bytearray, but got 'int'

This would be much easier to answer with a line number.
My guess might be that you are trying to convert an int to an int here:
port=int(os.getenv('PORT', 8080))
8080 is already an int. Does it work if you do:
port=int(os.getenv('PORT', '8080'))

Related

ImproperlyConfigured: circular import and also urls of project does have patterns in it

my url of project
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('learn.urls')),
]
url of my app
from django.urls import path
from .import views
urlpatterns = [
path('',views.home,name='home'),
path('notes',views.notes,name='notes'),
path('delete_note/<int:pk>',views.delete_note,name='delete_notes'),
path('detail/<int:pk>',views.detail.as_view(),name='detail'),
path('homework',views.work,name='homework'),
path('delete_hw/<int:pk>',views.delete_hw,name='delete_hw'),
path('update/<int:pk>',views.update,name='update'),
path('todo',views.todo,name=todo),
]
my views
from django.shortcuts import render,redirect
from .forms import *
from .models import *
from django.contrib import messages
from django.views.generic.detail import DetailView
def home(request):
return render(request,'website/home.html')
def notes(request):
if request.method == 'POST':
form= notesform(request.POST)
if form.is_valid():
notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description'])
notes.save()
messages.success(request,f"Notes of {request.user.username} is added successfully")
form = notesform()
notes= Notes.objects.filter(user=request.user)
context= {'notes':notes,'form':form}
return render(request,'website/notes.html',context)
def delete_note(request,pk=None):
Notes.objects.get(id=pk).delete()
return redirect('notes')
def work(request):
if request.method == 'POST':
form = homeworkform(request.POST)
if form.is_valid():
try:
finished = request.POST['is_finish']
if finished == 'on':
finished = True
else:
finished = False
except:
finished = False
homeworks= homework(
user= request.user,
subject = request.POST['subject'],
title = request.POST['title'],
description=request.POST['description'],
due= request.POST['due'],
is_finish = finished
)
homeworks.save()
else:
form = homeworkform()
Homework= homework.objects.filter(user=request.user)
context = {'Homework':Homework,'form':form}
return render(request,'website/hw.html',context)
def delete_hw(request,pk=None):
homework.objects.get(id=pk).delete()
return redirect('homework')
def update(request,pk=None):
Homework = homework.objects.get(id=pk)
if Homework.is_finish == True:
Homework.is_finish = False
else:
Homework.is_finish = True
Homework.save()
class detail(DetailView):
model = Notes
template_name = 'website/notes_detail'
redirect('notes')
def todo (request):
return render(request,'website/todo.html')
my models
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Notes(models.Model):
user= models.ForeignKey(User,on_delete=models.CASCADE)
title=models.CharField(max_length=200)
description=models.TextField()
def __str__(self):
return self.title
class homework(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
subject = models.CharField(max_length=100)
title = models.CharField(max_length=100)
description = models.TextField()
due = models.DateTimeField()
is_finish = models.BooleanField(default=False)
def __str__(self):
return self.title
class Todo(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
is_finish = models.BooleanField(default=False)
this is my codes i don't know the where and why this occurs
this is it shows
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'studyportal.urls' does not appear to have any patterns in it. If you see valid patterns
in the file then the issue is probably caused by a circular import.

OpenCV(4.5.2)/tmp/pip-req-build-eirhwqtr/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

I want to extract text from images that I had uploaded using django forms.
This is my view.py
from django.http.response import HttpResponseBadRequest
from django.shortcuts import render, redirect, reverse
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm
from django.contrib.auth.decorators import login_required
from .forms import UploadFileForm, EditFileName
from .models import Image
import cv2
import pytesseract
#login_required
def home(request):
context = {}
if request.method == "POST":
print(request.user)
form = UploadFileForm(request.POST, request.FILES)
print(request.FILES)
if form.is_valid():
username = request.user
image_text = request.FILES["image"].name
image = form.cleaned_data.get("image")
image_path = "../media/storage" + str(image)
image_clone = cv2.imread(image_path)
image_clone = cv2.cvtColor(image_clone, cv2.COLOR_BGR2GRAY)
image_clone = cv2.threshold(
image_clone, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
image_clone = cv2.medianBlur(image_clone, 5)
OCRtext = pytesseract.image_to_string(image_clone)
obj = Image.objects.create(
username=username,
image_text=image_text,
image=image,
OCRtext=OCRtext
)
obj.save()
print(obj)
else:
form = UploadFileForm()
form2 = EditFileName()
context['form2'] = form2
context['form'] = form
context['data'] = Image.objects.all()
print(context)
return render(request, "registration/success.html", context)
def edit(request):
context = {}
if request.method == "POST":
print('--------------')
form2 = EditFileName(request.POST)
if form2.is_valid():
username = request.user
image_text = form2.cleaned_data.get("image_text")
obj = Image.objects.filter(id=request.POST['image_id']).update(
image_text=image_text
)
print('obj in form2', obj)
form2 = EditFileName()
context['form2'] = form2
form = UploadFileForm()
context['form'] = form
context['data'] = Image.objects.all()
print(context)
return redirect('/home/')
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
I get this error -
File "/media/samarpan/DATA1/task/users/views.py", line 26, in home
image_clone = cv2.cvtColor(image_clone, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.2) /tmp/pip-req-build-eirhwqtr/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
The image uploaded by django form is being stored in request.FILES. I need to get the image path.
I understand that this error is because the image source isn't right in image_path = "../media/storage" + str(image) - What is the fix?
repo link - https://github.com/smrpn/task/
I were also getting the similar type of error
"error: OpenCV(4.5.2) /tmp/pip-req-build-eirhwqtr/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'"
But its because I mistakenly give wrong path of images.

How to capture a field instance during django-import-export upload

I'd like to import data into my resource minus the school field because the logged in user already belongs to a specific school. How would I do it without having the school field in my excel???
class uploadStudents(LoginRequiredMixin,View):
context = {}
def get(self,request):
form = UploadStudentsForm()
self.context['form'] = form
return render(request,'upload.html',self.context)
def post(self, request):
form = UploadStudentsForm(request.POST , request.FILES)
data_set = Dataset()
if form.is_valid():
file = request.FILES['file']
extension = file.name.split(".")[-1].lower()
resource = ImportStudentsResource()
if extension == 'csv':
data = data_set.load(file.read().decode('utf-8'), format=extension)
else:
data = data_set.load(file.read(), format=extension)
result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True)
if result.has_validation_errors() or result.has_errors():
messages.success(request,f'Errors experienced during import.')
print("error", result.invalid_rows)
self.context['result'] = result
return redirect('import_students')
else:
result = resource.import_data(data_set, dry_run=False, raise_errors=False)
self.context['result'] = None
messages.success(request,f'Students uploaded successfully.')
else:
self.context['form'] = UploadStudentsForm()
return render(request, 'upload.html', self.context)
The resource
class ImportStudentsResource(resources.ModelResource):
school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name'))
klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name'))
stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name'))
class Meta:
model = Student
fields = ('school','student_id','name','year','klass','stream')
import_id_fields = ('student_id',)
import_order = ('school','student_id','name','year','klass','stream')
Either remove 'school' from your 'fields' declaration, or add it to the 'exclude' list.
docs
Edit
To include a school_id which is associated with the logged in user, you'll need to create the Resource with this school_id:
Resource
class ImportStudentsResource(resources.ModelResource):
def __init__(self, school_id):
super().__init__()
self.school_id = school_id
def before_save_instance(self, instance, using_transactions, dry_run):
instance.school_id = self.school_id
post()
def post(self, request):
# skipped existing code
school_id = get_school_id_from_logged_in_user(self.request)
resource = ImportStudentsResource(school_id)

Getting the post instance in Django class based views

I currently use a function based view to let users write comments on posts, but I'm trying to convert it to class based views
Function views.py
def comment(request, pk):
form = CommentForm(request.POST)
# Post instance
post_instance = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
if form.is_valid:
obj = form.save(commit=False)
obj.commenter = request.user
obj.post = post_instance
obj.save()
return redirect('/')
else:
messages.error(request, 'Comment Failed')
return render(request, 'comment.html', {'form': form})
Class views.py
class CommentView(FormView):
template_name = 'comment.html'
form_class = CommentForm
success_url = '/'
def get_object(self):
pk = self.kwargs.get('pk')
post_instance = get_object_or_404(Post, pk=pk)
return post_instance
def form_valid(self, form):
obj = form.save(commit=False)
obj.commenter = self.request.user
obj.post = post_instance
obj.save()
return super().form_valid(form)
I'm trying to implement the same logic for saving the comment but I get the error: name 'post_instance' is not defined
get_object() is returning the 'post_instance' variable but I can't access it.
Could you guys show me where I'm doing a mistake, thanks in advance!
You can try:
class CommentView(FormView):
template_name = 'comment.html'
form_class = CommentForm
success_url = '/'
def get_object(self):
pk = self.kwargs.get('pk')
post_instance = get_object_or_404(Post, pk=pk)
return post_instance
def form_valid(self, form):
obj = form.save(commit=False)
obj.commenter = self.request.user
obj.post = self.get_object()
obj.save()
return super().form_valid(form)

Access app_context from custom Converter in Quart

Is there a solution to get the app context in a class that inherit werkzeug BaseConverter class?
This is my example running in Flask:
from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
app = None
def to_python(self, value):
# Create an app context to get value from db
# and instantiate a class X as obj
return obj
def to_url(self, obj):
value = obj.code
title = obj.title
return "%s/%s"%(value, title)
def crate_app():
...
app.url_map.converters['code'] = CodeConverter
CodeConverter.app = app
...
Well, this works for me.
from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
app = None
async def get_object(self, app, value):
async with app.app_context():
# and instantiate a class X as obj
return obj
def to_python(self, value):
pool = concurrent.futures.ThreadPoolExecutor()
result = pool.submit(asyncio.run, self.get_object(self.__class__.app, value)).result()
return result
def to_url(self, obj):
value = obj.code
title = obj.title
return "%s/%s"%(value, title)
def crate_app():
...
app.url_map.converters['code'] = CodeConverter
CodeConverter.app = app
...

Resources