wkhtmltopdf reported an error: Exit with code 1 due to network error: ContentNotFoundError - django-models

good day, please im having this error when i click Export to pdf button…………………
‘’’
views.py
#login_required(login_url='loginpage')
#cache_control(no_cache=True, must_rev alidate=True, no_store=True)
def exportToPdf(request, pk):
c = get_object_or_404(candidate, id=pk)
cookies = request.COOKIES
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'cookie' : [
('csrftoken', cookies ['csrftoken']),
('sessionid', cookies ['sessionid'])
]
}
pdf = pdfkit.from_url('http://127.0.0.1:8000/'+str(c.id), False, options = options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-disposition'] = 'attachment; filename=candidate.pdf'
return response
urls.py
path('int:pk/exporttopdf/', views.exportToPdf, name='exporttopdf'),
‘’’

Related

irregular arbitrarily Cross-Origin request blocked error in Django on Ionos hosting

I am currently making a quiz project for school. The quiz is supposed to evaluate in the front-end, which works perfectly fine, and after that it should send the information to the backend. The backend should save the details to the database and after that it should send the information back to the front-end. The front-end should show a message with some details about how you performed compared to all the others, the information is gotten from the database.
So, the weird thing about all that is that it works sometimes and sometimes not. If I test it on localhost, the code works perfectly fine. The error only occurs on the Ionos server (I got a hosting contract so I do not have access to the console).
Here is the link to my website: https://tor-netzwerk-seminarfach2024.com/ . If you click on the upper left corner and then on the quiz button, you will get to the quiz. If I look at the console and network analytics, when the error occurs, the following message shows up:
Cross-Origin request blocked: The same source rule prohibits reading
the external resource on https://api. tor-netzwerk-seminarfach2024.
com/apache-test/. (Reason: CORS request failed).
https://api.tor-netzwerk-seminarfach2024.com/apache-test/ is my backend and https://tor-netzwerk-seminarfach2024.com/ is my front-end.
The settings file in Django is not the problem. To make it clear, the error does not occur always. Sometimes you have to go again to the website and try it one a few more times until you get the error.
If I look at the network analytics, then I see that the client request works as usual, but the answer field from the server is completely empty. Let's move on to the weirdest part of all: the Data actually gets saved in the Database, there is just sometimes no response?
It would be way to much for a minimum working product but here is the most important code. If you want to test it you can just visit the link to my Website:https://tor-netzwerk-seminarfach2024.com/
Server side with Django
from rest_framework.response import Response
from .models import Lead
import json
from .serializer import TestingSerializer
def updateDigits():
leadObj = Lead.objects.all()
currentScore = leadObj[0].sumScore; currentRequests = leadObj[0].sumRequests
valueBtnOne = leadObj[0].buttonOne; valueBtnTwo = leadObj[0].buttonTwo;
valueBtnThree = leadObj[0].buttonThree; valueBtnFour = leadObj[0].buttonFour;
valueBtnFive = leadObj[0].buttonFive; valueBtnSix = leadObj[0].buttonSix;
valueBtnSeven = leadObj[0].buttonSeven; valueBtnEight = leadObj[0].buttonEight;
valueBtnNine = leadObj[0].buttonNine;
return [valueBtnOne,valueBtnTwo,valueBtnThree,valueBtnFour,valueBtnFive,valueBtnSix,valueBtnSeven,valueBtnEight,valueBtnNine,currentScore,currentRequests]
#api_view(["POST"])
def home(request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
result = body["Result"]
isItRight = body["whichOnesRight"]
ip_adress = get_client_ip(request)
queryset = Lead.objects.all()
if Lead.objects.all().exists():
currentValues = updateDigits()
queryset.update(
sumScore = result + currentValues[9],
sumRequests = 1 + currentValues[10],
buttonOne = currentValues[0] + isItRight[0],
buttonTwo = currentValues[1] + isItRight[1],
buttonThree = currentValues[2] + isItRight[2],
buttonFour = currentValues[3] + isItRight[3],
buttonFive = currentValues[4] + isItRight[4],
buttonSix = currentValues[5] + isItRight[5],
buttonSeven = currentValues[6] + isItRight[6],
buttonEight = currentValues[7] + isItRight[7],
buttonNine = currentValues[8] + isItRight[8],
)
currentValues = updateDigits()
else:
obj = Lead()
obj.save()
serializer = TestingSerializer(queryset[0], many =False)
return Response({**serializer.data, "myResult": result})
The Django model
from django.db import models
class Lead(models.Model):
sumScore = models.IntegerField(default=0)
sumRequests = models.IntegerField(default=0)
buttonOne = models.IntegerField(default=0)
buttonTwo = models.IntegerField(default=0)
buttonThree = models.IntegerField(default=0)
buttonFour = models.IntegerField(default=0)
buttonFive = models.IntegerField(default=0)
buttonSix = models.IntegerField(default=0)
buttonSeven = models.IntegerField(default=0)
buttonEight = models.IntegerField(default=0)
buttonNine = models.IntegerField(default=0)
serializer just serializes _ _ all _ _ ...
Front end with React
function evaluateAndCheckQuiz(){
let countNotChosen = howManyNotChosen()
if(countNotChosen){ answerQuestions(countNotChosen); return }
let points = evaluateQuiz()
document.getElementById("scoreText").style.display = "block"
document.getElementById("scoreNumber").textContent = points
return points
}
Calling sendAndGetQuizAverage with evaluateAndCheckQuiz as a parameter
function sendAndGetQuizAverage(points){
const myPostRequest = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({"Result":points, "whichOnesRight": whichOnesRight}),
};
let data
fetch('https://api.tor-netzwerk-seminarfach2024.com/apache-test/', myPostRequest).then(
(response) => data = response.json()).then(
(data) => {showResultAnalyse(data)})
}
function showResultAnalyse(data){
console.log(data)
let averageScore = (data["sumScore"] / data["sumRequests"]).toFixed(2)
let myResult = data["myResult"]
changeLinksToStatistics([
data["buttonOne"],data["buttonTwo"],data["buttonThree"],
data["buttonFour"],data["buttonFive"],data["buttonSix"],
data["buttonSeven"],data["buttonEight"],data["buttonNine"]
],
data["sumRequests"]
)
swal(
{
text:`${checkWhichText(myResult,averageScore,data["sumRequests"] )}`,
icon: myResult > averageScore ?"success": "error",
button:"Oki doki",
}
);
}

getting google oauth to work with flask, react, postgresql. keep getting internal server error and cors errors

I'm trying to get google oauth to work with flask and react. When I run the server and try to log in, the google sign-in window pops up and immediately closes down and I get an internal server error. in my flask terminal I get this error:
raise MissingCodeError("Missing code parameter in response.")
oauthlib.oauth2.rfc6749.errors.MissingCodeError: (missing_code) Missing code parameter in response.
Any thoughts?
app.py
#app.route('/login', methods=['POST'])
#cross_origin()
def login():
google_provider = get_google_provider()
auth_endpoint = google_provider["authorization_endpoint"]
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "/callback",
scope=["openid", "email", "profile"]
)
return redirect(request_uri)
#app.route('/login/callback', methods=['GET', 'POST'])
#cross_origin()
def login_callback():
code = request.json.get("access token")
print("**************")
# print(list(request.args.keys()))
print(request.json)
print("**************")
token, headers, body = client.prepare_token_request(
token_endpoint,
code=code,
authorization_response=request.url,
redirect_url=request.base_url
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET)
)
client.parse_request_body_response(json.dumps(token_response.json()))
userinfo_endpoint = google_provider["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = request.get(uri, headers=headers, data=body)
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
user_email = userinfo_response.json()["email"]
user_picture = userinfo_response.json()["picture"]
user_name = userinfo_response.json()["given_name"]
user_member_since = datetime.today().strftime('%Y-%m-%d')
else:
print("User email not available or not verified by Google")
user = User(id=unique_id, name=user_name, email=user_email, picture=user_picture, member_since=user_member_since)
if not User.get(unique_id):
User.create(unique_id, user_name, user_email, user_picture, user_member_since)
login_user(user)
redirect(url_for("/new-user-form"))
app.js
googleResponse = (response) => {
const tokenBlob = new Blob([JSON.stringify({access_token: response.accessToken}, null, 2)], {type: 'application/json'});
const options = {
method: 'POST',
body: tokenBlob,
mode: 'cors',
cache: 'default'
}
fetch(`${BASE_URL}/login/callback`, options).then(r => {
if (r.headers.get('Content-Type') === 'text/html; charset=utf-8') {
console.log('error')
return
}
const token = r.headers.get('x-auth-token')
r.json().then(user => {
if (token) {
this.setState({isAuthenticated: true, user, token, message: `${user.name}`})
console.log(token)
}
});
})
}
onFailure = (error) => {
alert(error.data)
}
<Route path='/login'>
<GoogleLogin
clientId={config.GOOGLE_CLIENT_ID}
buttonText="Login"
onSuccess={this.googleResponse}
onFailure={this.onFailure}
/>

The requested URL "localhost/pusher/auth" was not found on this server

i am trying to build a video chat web application using laravel for backend and reactjs for frontend. i tried to find the errors here, but i couldn't. please help me to fix my errors.
Errors that are showing:
1/ POST http://localhost/pusher/auth 404 (Not Found)
2/ Pusher : : ["Error: Unable to retrieve auth string from auth endpoint - received status: 404 from /pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users"]
My Code from "resources/js/components/App.js"
setupPusher(){
Pusher.logToConsole = true;
this.pusher = new Pusher(APP_KEY,{
authEndpoint: '/pusher/auth',
cluster: 'ap2',
auth:{
params: this.user.id,
headers:{
'X-CSRF-Token': window.csrfToken
}
}
});
this.channel = this.pusher.subscribe('presence-video-channel');
this.channel.bind(`clnt-signal-${this.user.id}`,(signal) => {
let peer = this.peers[signal.userId];
// if peer is not already exists, we got an incoming call
if(peer == undefined){
this.setState({otherUserId: signal.userId});
peer = this.startPeer(signal.userId, false);
}
peer.signal(signal.data);
});
}
My Code from "routes/web.php"
Route::post('/pusher/auth', [App\Http\Controllers\HomeController::class, 'authenticate']);
My Code from "app/Http/Controllers/HomeController.php"
public function authenticate(Request $request){
$socketId = $request->socket_id;
$channelName = $request->channel_name;
$pusher = new Pusher('a384f250f86af1f16f98', 'd30d380941bdec2e4e55', '1147033', [
'cluster' => 'ap2',
'useTLS' => true
]);
$presence_data = ['name' => auth()->user()->name];
$key = $pusher->presence_auth($channelName, $socketId, auth()->id(), $presence_data);
return response($key);
}

GET API showing KeyError in browser, but working in Postman

I have encountered a strange problem where the GET API that I created was working fine in Postman, but not working at that specific URL when entered in the browser.
Here is what the input and output should look like as shown successfully in Postman: Trying API in Postman
Here is what the error is showing on my browser: Error in browser
I am also getting this error in React about CORS headers even though I have added in code to try to handle that issue: Error in React about CORS
Here is the code in settings.py in Django:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Prediction',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Here is the code in local_settings.py in Django:
#########################################
## IMPORT LOCAL SETTINGS ##
#########################################
try:
from .local_settings import *
except ImportError:
pass
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
#################################################################
## (CORS) Cross-Origin Resource Sharing Settings ##
#################################################################
CORS_ORIGIN_ALLOW_ALL = True
I also tried adding this code in index.js in React to handle the CORS headers problem but it didn't work:
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/jokes/random', (req, res) => {
request({
url: 'https://joke-api-strict-cors.appspot.com/jokes/random'
},
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({
type: 'error',
message: err.message
});
}
res.json(JSON.parse(body));
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Here is the code in App.js in React:
import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios';
function App() {
const [json_response1, set_json_response1] = useState("1st algorithm - List of similar events");
function request_json_response() {
axios.get('http://127.0.0.1:8000/api/get_events_1st_alg', {
data: {
"ID": "User_ID1"
}
}).then(function (response) {
// handle success
set_json_response1(response);
});
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
{json_response1}
</p>
<button onClick={request_json_response}>
Generate events for user
</button>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Here is the code in views.py in Django:
class get_events_1st_alg(APIView):
def get(self, request, format=None):
"""
data = request.data
banana_dictionary = {'banana':17}
return Response(banana_dictionary, status=status.HTTP_201_CREATED)
"""
import pandas as pd
import numpy as np
import psycopg2
import sqlalchemy
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import pairwise_distances
import requests
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:postgres#localhost/postgres')
# pd.read_sql_query('''SELECT * FROM arts_user_interaction LIMIT 5;''', engine)
events = pd.read_sql_query('''SELECT * FROM arts_event;''', engine)
Ratings = pd.read_sql_query('''SELECT * FROM arts_user_interaction;''', engine)
Mean = Ratings.groupby(by="User_ID", as_index = False)['User Rating'].mean()
Rating_avg = pd.merge(Ratings, Mean, on = "User_ID")
Rating_avg['adg_rating']=Rating_avg['User Rating_x']-Rating_avg['User Rating_y']
check = pd.pivot_table(Rating_avg,values='User Rating_x',index='User_ID',columns='Event_ID')
final = pd.pivot_table(Rating_avg,values='adg_rating',index='User_ID',columns='Event_ID')
final_event = final.fillna(final.mean(axis=0))
final_user = final.apply(lambda row: row.fillna(row.mean()), axis=1)
cosine = cosine_similarity(final_event)
np.fill_diagonal(cosine, 0 )
similarity_with_event =pd.DataFrame(cosine,index=final_event.index)
similarity_with_event.columns=final_user.index
def find_n_neighbours(df,n):
order = np.argsort(df.values, axis=1)[:, :n]
df = df.apply(lambda x: pd.Series(x.sort_values(ascending=False)
.iloc[:n].index,
index=['top{}'.format(i) for i in range(1, n+1)]), axis=1)
return df
sim_user_30_e = find_n_neighbours(similarity_with_event,30)
def get_user_similar_events( user1, user2 ):
common_events = Rating_avg[Rating_avg.User_ID == user1].merge(
Rating_avg[Rating_avg.User_ID == user2],
on = "Event_ID",
how = "inner" )
return common_events.merge(events, on ='Event_ID')
a = get_user_similar_events('User_ID10','User_ID220')
a = a.reindex(columns= ['User Rating_x_x','User Rating_x_y','Name'])
Rating_avg = Rating_avg.astype({"Event_ID": str})
Movie_user = Rating_avg.groupby(by = 'User_ID')['Event_ID'].apply(lambda x:','.join(x))
def User_item_score1(user):
Movie_seen_by_user = check.columns[check[check.index==user].notna().any()].tolist()
a = sim_user_30_e[sim_user_30_e.index==user].values
b = a.squeeze().tolist()
d = Movie_user[Movie_user.index.isin(b)]
l = ','.join(d.values)
Movie_seen_by_similar_users = l.split(',')
Movies_under_consideration = list(set(Movie_seen_by_similar_users)-set(list(map(str, Movie_seen_by_user))))
Movies_under_consideration = list(map(str, Movies_under_consideration))
score = []
for item in Movies_under_consideration:
c = final_event.loc[:,item]
d = c[c.index.isin(b)]
f = d[d.notnull()]
avg_user = Mean.loc[Mean['User_ID'] == user,'User Rating'].values[0]
index = f.index.values.squeeze().tolist()
corr = similarity_with_event.loc[user,index]
fin = pd.concat([f, corr], axis=1)
fin.columns = ['adg_score','correlation']
fin['score']=fin.apply(lambda x:x['adg_score'] * x['correlation'],axis=1)
nume = fin['score'].sum()
deno = fin['correlation'].sum()
final_score = avg_user + (nume/deno)
score.append(final_score)
data = pd.DataFrame({'Event_ID':Movies_under_consideration,'score':score})
top_5_recommendation = data.sort_values(by='score',ascending=False).head(5)
Movie_Name = top_5_recommendation.merge(events, how='inner', on='Event_ID')
Movie_Names = Movie_Name.Name.values.tolist()
return Movie_Names
# user = input("Enter the user id to whom you want to recommend : ")
data = request.data
user = ""
for i, v in data.items():
user = str(v)
predicted_movies = User_item_score1(user)
return Response(predicted_movies, status=status.HTTP_201_CREATED)
I really don't know what I am doing as I am just following a bunch of tutorials online so I would love it if anyone can help with resolving the API issue in the browser and the React issue with CORS in the browser as well. Thank you so much!
The problem is that GET request shouldn't have body (it is not specified/supported by axios). See this issue in axios repository: link.
Please do a change from data to params:
axios.get('http://127.0.0.1:8000/api/get_events_1st_alg', { params: { "ID":"User_ID1"}})
And access it in DRF like:
user = request.query_params.get("ID")
Your CORS config is OK.

Axios post request is being denied by flask made api. CORS error coming up [duplicate]

This question already has an answer here:
cors enable in Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
(1 answer)
Closed 2 years ago.
I am trying to add user from my react application through an API made with flask. But the post request is getting in error with the following error.
'http://localhost:5000/api/v1.0/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
my axios code is following
const params = {
user_name : '5678234121',
passwd : 'password',
location : 'Kolkata',
pin_code : '700019',
secret_ques: 'What is your mother s maiden name?',
answr : 'aba',
status : 'Active',
remarks : 'test data'
};
const res = await Axios.post(
'http://localhost:5000/api/v1.0/add', params, {
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
});
console.log(res.data);
my flask code is following
#app.route('/api/v1.0/add', methods=["POST"])
def add():
con = None
db = datadir + datafile
try:
_json = request.json
_name = _json['user_name']
_psswd = _json['passwd']
_locatn = _json['location']
_pincd = _json['pin_code']
_secrt = _json['secret_ques']
_ans = _json['answr']
_stat = _json['status']
_remks = _json['remarks']
# validate the received values
if _name and _psswd and _pincd and request.method == 'POST':
#do not save password as a plain text
_hashed_password = base64.b64encode(_psswd.encode("utf-8"))
# save edits
sql = '''INSERT INTO user_mast(user_name, passwd, location, pin_code, secret_ques, answr, status, remarks ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'''
data = (_name, _hashed_password.decode('ASCII'), _locatn, _pincd, _secrt,_ans, _stat, _remks , )
con = sqlite3.connect( db ) # Connection to database
cur = con.cursor()
cur.execute(sql, data)
con.commit()
resp = jsonify({'Status' : 'User added successfully!'})
resp.status_code = 200
else :
resp = jsonify ({'Status' :'Mandatory fields: Name,Password,Pincode missing..'})
resp.status_code = 502
except sqlite3.Error as e:
resp = jsonify({'Status' :'Database Error'})
resp.status_code = 500
except Exception as e:
print(e)
resp = jsonify({'Status' :'Unknown Error : Contact Administrator'})
resp.status_code = 501
finally:
cur.close()
con.close()
return resp
Please help me to fix the error, going clueless about this.
If you're new to this, I'd recommend just adding Flask-CORS to your application and not futzing around with the headers.

Resources