Access delete method body send via axios.delete - python

I am building a react-django simple blog app and I am trying to delete blog post but I also want to send body with delete to backend But I have no idea, How can I access delete body ?. I can do with post like self.request.POST with how with delete ?
App.js:
class BlogPost extends React.Component {
deleteBlog = (blog_title) => {
const body = ({title: blog_title});
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
}
axios.delete("delete_blog/", blog_title, {headers:headers}).then(res => {console.log})
}
render() {
return (
<div>
{
this.state.blogs.map(res => <div>
{res.blog_title}
<button onClick={() => deleteBlog(res.blog_title)}></button>
</div>
}
</div>
)}}
views.py:
class BlogPost(APIView):
def post(self, *args, **kwargs):
.......
def delete(self, *args, **kwargs):
# Trying to access delete body here......
print(self.request.POST)
# It printed empty dict like <[QueryDict = {}]>
I have tried many times but it is still not showing.

To Use Axios Delete request with body , you need to use axios.delete(url,{ headers: { "Authorization": "***" }, data: { } } );
eg:
axios.delete("delete_blog/", {
headers: headers,
data: {
source: blog_title
}
});

Related

How do i upload a file from a website to imgur using python and flask

My html code:
<form method="post" action="" enctype="multipart/form-data">
<input id="file-upload" type="file" name="file-upload" style="display:none;" accept="image/png, image/jpeg, image/jpg">
<button class="avatar_button"
id="file-button"
name="coose_avatar"
onclick="document.getElementById('file-upload').click()"
style="cursor: pointer;"
>Choose file</button>
<script>
document.getElementById("file-upload").addEventListener("change", function() {
var file = this.files[0];
var formData = new FormData();
formData.append("file-upload", file);
fetch("/profile", {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(response => response.json())
.then(data => {
document.getElementById("avatar_input").value = data.link;
})
});
</script>
and my python code:
def upload_to_imgur(image_path):
client_id = ""
api_key = ""
url = "https://api.imgur.com/3/image"
headers = {
"Authorization": f"Client-ID {client_id}"
}
with open(image_path, "rb") as image:
data = {
"image": image.read(),
"type": "file"
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
response_json = response.json()
return response_json["data"]["link"]
else:
return None
#app.route("/profile", methods=["GET", "POST"])
def profile():
if request.method == "POST":
print(request.form)
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
if
alot of other things
elif request.form.get("file-uploader") == "file-uploader":
print("yes")
# sleep(5)
if 'file-upload' in request.files:
image = request.files["file-upload"]
name=session["username"]
imagename = name
image.save(imagename)
imgur_link = upload_to_imgur(imagename)
print(imgur_link)
it should make a imgur post and print the link but when i try to upload the file, the code already tried to run. how do i make it working and/or start the python code when the file is selected.
I; ve tried many things but it just wont work
can anyone help me?

How to update a state using useState hook in react?

Im a beginner in react, and I was trying to experiment with the useState Hook. I have a react file where I am fetching data from the database in flask which looks like this
import React, {useState, useEffect,useContext } from 'react'
import { Context } from "../../store/appContext"
function Main() {
const {store, actions} = useContext(Context)
const [notes, updateNotes] = useState([])
let arr =[];
const Notes = async () => {
const resp = await fetch('/main/', {
method: "GET",
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Authorization':"Bearer " + store.token
},
});
if(resp.status === 200) {
const data = await resp.json();
arr = data.data
arr.forEach(note => {
updateNotes(...notes, note);
})
console.log("Array data",arr)
updateNotes(...notes, arr);
console.log("state data",notes);
}
}
useEffect(() => {
actions.getTokenAfterRefresh();
Notes();
}, []);
return (
<>
HEy this is thee main page!!!
<div>
Welcome {store.user}!
</div>
<div>
{/* {numNotes == 0 ?
<div>
Create a new note
</div>
:
<div>
Display notes
</div> */}
}
</div>
</>
)
}
export default Main
The flask api looks like this:
from flask import (request, Blueprint, jsonify, g)
from flask_jwt_extended import jwt_required
from flask_jwt_extended import get_jwt_identity
from PIM.db import get_db
bp = Blueprint('main', __name__, url_prefix='/main')
#bp.route('/',methods=('GET', 'POST'))
#jwt_required()
def mainPage():
num=0;
data =[];
if request.method == 'GET':
db = get_db()
user = get_jwt_identity()
if user is not None:
userdata = db.execute('SELECT Info, Title from UserNotes INNER JOIN Users ON Users.Id = UserNotes.user WHERE Users.username = ?',[user]).fetchall()
for row in userdata:
data.append(list(row));
return jsonify({'data': data}), 200
When I try to console log the data in arr variable it displays the data correctly. But when i log the data in the state it doesnt display any data.
Could you please help me solve this issue and also suggest why this is happening.
Thank you
Becasuse setState in asynchronous. State notes only update new value when component re-render. You can check new value of note by using console.log before retrun`
console.log("state data",notes);
return (...)

Stripe IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId

I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new r (https://js.stripe.com/v3/:1:6143)
at Js (https://js.stripe.com/v3/:1:165350)
at $s (https://js.stripe.com/v3/:1:165646)
at https://js.stripe.com/v3/:1:166758
at Qs (https://js.stripe.com/v3/:1:166769)
at nc (https://js.stripe.com/v3/:1:167275)
at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030)
at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39
Here's the Vue.js method responsible for this:
<script src="https://js.stripe.com/v3/"></script>
<script>
const PlansApp = {
data() {
return {
}
},
delimiters: ['[[', ']]'],
methods: {
subscribe(plan) {
console.log('Subscribe:', plan);
const stripe = Stripe('{{ stripe_pub_key }}');
fetch('/dashboard/myaccount/teams/api/create_checkout_session/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({
'plan': plan
})
})
.then(function(response) {
return response.json()
})
.then(function(session) {
console.log(session)
return stripe.redirectToCheckout({ sessionId: session.sessionId })
})
.then(function(result) {
if (result.error) {
console.log('Error:', result.error.message)
}
})
.catch(function(error) {
console.log('Error:', error);
});
}
}
}
Vue.createApp(PlansApp).mount('#plans-app')
</script>
And here's the Django code that creates the session on the backend:
#login_required
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
plan = data['plan']
if plan == 'basic':
price_id = settings.STRIPE_BASIC_PRICE_ID
else:
price_id = settings.STRIPE_PRO_PRICE_ID
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id = request.user.userprofile.active_team_id,
success_url = '%s%s?session_id={CHECKOUT_SESSION_ID}' % (settings.WEBSITE_URL, reverse('team:plans_thankyou')),
cancel_url = '%s%s' % (settings.WEBSITE_URL, reverse('team:plans')),
payment_method_types = ['card'],
mode = 'subscription',
line_items = [
{
'price': price_id,
'quantity': 1
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
I'm struggling to find out why I'm getting the error that I'm getting and would be grateful for any help!
I guest the problem come from the 'success_url' and the 'cancel_url'.
Try to add http:// or https:// in your url
Cordially

Uncaught TypeError: Super expression must either be null or a function [duplicate]

This question already has answers here:
Reactjs, Super expression must either be null or a function
(2 answers)
Closed 5 years ago.
So I'm new to React and even though I've found multiple others having the same issue, I still haven't found the error in my code. Therefore I turn to you stackoverflow, you're my only hope!
I am learning, so I wanted to create a simple ReactJS application that handles a HTTP-request. After finishing the code I encountered the error:
Uncaught TypeError: Super expression must either be null or a function, not object
at exports.default (inherits.js?0578:21)
at eval (app.js?71f7:22)
The error persists even though I've tried a lot of different changes and I am fairly certain that it's related to imports/exports as this is what a lot of other sources tell me, although double-checking imports etc. hasn't yielded any results.
The code:
app.js ( handles the rendering of a simple button and should execute a simple GET request on click )
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createServerSagaRequest } from '../saga/serverSaga'
import { incrRequestAmount, requestSelector } from '../reducer/requestReducer'
const mapStateToProps = (state) => {
return {
getRequestAmount: requestSelector.requests(state),
}
}
const mapDispatchToProps = (dispatch) => {
return {
open: (url, data, action, method) => dispatch(createServerSagaRequest((url, data, action, method))),
requests: () => dispatch(incrRequestAmount()),
}
}
class App extends React {
constructor(props){
super(props)
}
_buttonClick() {
this.props.requests()
this.props.open("http://mvctestproject.local/GetData", "TestDataFraGet", action, "GET")
}
render(){
return (
<button
className="btn btn-default"
onClick={this._buttonClick()}>{this.props.getRequestAmount()}
</button>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
serverSaga.js (my saga which can access the reducer and service)
import React, { Component } from 'react'
import { put, call, take, fork, select } from 'redux-saga/effects'
import { callServer } from '../service/serverService'
import { incrRequestAmount, requestSelector } from '../reducer/requestReducer'
export function createServerSagaRequest() {return { type: CREATE_REQUEST }}
function* handleRequest(url, data, action, method, success){
incrRequestAmount()
return yield executeRequest(url, data, action, method, success)
}
function* executeRequest(url, data, action, method, success) {
let response = yield call(callServer, url, method, data)
let responseSuccess = response && response.Succeeded
return
}
export default function* serverSaga(){
yield [
fork(function*(){
yield call (CREATE_REQUEST, handleRequest)
}),
]
}
rootSaga.js ( grouping sagas - in case I made more )
import { fork } from 'redux-saga/effects'
import serverSaga from './serverSaga'
export default function* rootSaga(){
yield [
fork(serverSaga)
]
}
requestReducer.js ( only function is to increment a variable after each request)
import { fromJS } from 'immutable'
export function incrRequestAmount() {return {type: 'INCR_REQUESTS'}}
const initialState = {
requestAmount: 0
}
function requestReducer(state = fromJS(initialState), action){
switch(action.type){
case 'INCR_REQUESTS':
return state.updateIn(["requestAmount"], (requests) => requests++)
default:
return state
}
}
export const requestSelector = {
amount: state => state.requests.get('requestAmount')
}
export default requestReducer
reducers.js ( grouping reducers - in case i made more )
import { combineReducers } from 'redux'
import React, { Component } from 'react'
import requests from './requestReducer'
export default combineReducers({
requests,
})
serverService.js ( handles calls to the server (GET/POST)
import React, { Component } from 'react'
export function callServer(url, bodyData, method){
let methodType = method.toLowerCase()
return new Promise((resolve, reject) => {
let r;
switch (methodType){
case 'post':
r = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyData)
}
break;
case 'get':
r = {
method: 'GET'
}
break;
}
if (r) {
console.log("URL: ", url)
fetch(url, r)
.then((response) => {
console.log("Resp: ", url, response)
return response.json()
})
}
})
}
You need to extend React.Component to create a component, not React itself:
class App extends React {
should be
class App extends React.Component {
, or since you imported Component directly
class App extends Component {

How To Pagination Angular2 with Django Rest Framework API

I am trying to create a simple blog application using Angular2 with Django Rest Framework.
I am implementing pagination in Django, but I do not know how to rendering it in Angular.
API has the following structure.
Entries are paginated every 5 entries.
ng2app/src/app/models/entries.model.ts
export interface IEntries {
count: any,
next: any,
previous: any,
results: IResults[]
}
export interface IResults {
title: string,
body: string,
created_at: any,
updated_at: any
}
ng2app/src/app/services/entries.service.ts
import { Injectable } from "#angular/core";
import { Http } from "#angular/http";
import 'rxjs/add/operator/toPromise';
import { IEntries } from '../models/entries.model';
#Injectable()
export class EntriesService {
constructor(
private http: Http
){
}
getEntries(page: number){
return this.http
.get(`http://127.0.0.1:8000/api/entries/?limit=5&offset=` +((page * 5)-5))
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
ng2app/src/app/services/entries.component.ts
import { Component, OnInit } from '#angular/core';
import { EntriesService } from '../services/entries.service';
import { IEntries } from '../models/entries.model';
#Component({
selector: 'my-entries',
templateUrl: '../templates/entries.component.html',
styleUrls: ['../static/entries.component.css']
})
export class EntriesComponent implements OnInit{
title = 'entries';
entries: IEntries[] = [];
error: any;
public constructor(
private entriesService: EntriesService,
){}
getEntires(page :number) {
this.entriesService
.getEntries(page)
.then(entries => this.entries = entries)
.catch(error => this.error = error);
}
ngOnInit() {
this.getEntires(1);
}
}
ng2app/src/app/templates/entries.component.html
<div class="container">
<h2>{{title}}</h2>
<div class="panel panel-default" *ngFor="let results of entries.results">
<div class="panel-heading">{{ results.title }}</div>
<div class="panel-body pre-wrap" ng-bind="multiLineText">{{ results.body }}</div>
<div class="panel-footer">{{ results.created_at | date}}</div>
</div>
<nav *ngIf="entries.count > 5">
(I want to display pagination here)
</nav>
</div>
In such a case, please help how to implement Pagination.
After implementing pagination in the Django backend, querying the backend would return results in the following format:
"data": {
"count": ,
"next": "",
"previous": "",
"results": []
}
count: The total number of items returned.
next: The URL to the next items after performing pagination
previous: The URL to the previous items after you have navigated to the next. set of items
results: The items requested for from the backend, paginated obviously i.e if pagination was set to 10 items and 15 were returned, results would return 10 items on the first request, then after navigating to the URL in next, results would return the remaining 5.
Service
#Injectable({
providedIn: "root"
})
export class OurService {
constructor(private http: HttpClient) {}
// Here,we make our request to the backend API, this observer takes in the backend
// api url as a parameter and performs a GET request
getAllTransactions(APIUrl: string): Observable<any> {
return this.http.get<>(APIUrl);
}
}
Component
#Component({
selector: "app-transactions",
templateUrl: "./transactions.component.html",
styleUrls: ["./transactions.component.scss"]
})
export class TransactionsComponent implements OnInit {
transactions: Transacton[];
transactionsUrl = "http://.../api/v1/transactions/"; //url to query for the transactions
next: string;
previous: string;
constructor(private transactionService: TransactionService) {}
ngOnInit(): void {
// On component initialization, load the transactions on the page
this.getTransactions(this.transactionsUrl);
}
getTransactions(url: string) {
this.transactionService.getAllTransactions(url).subscribe(res => {
this.transactions = res.data.results;
if (res.data.next) {
// set the components next transactions here from the response
this.next = res.data.next;
}
if (res.data.previous) {
// set the components previous transactions here from the response
this.previous = res.data.previous;
}
});
}
// function fetches the next paginated items by using the url in the next transactions
fetchNext() {
this.getTransactions(this.next);
}
// function fetches the previous paginated items by using the url in the previous transactions
fetchPrevious() {
this.getTransactions(this.previous);
}
HTML
<div class="page-buttons">
<button class="btn prev" (click)="fetchPrevious()">
</button>
<button class="btn next" (click)="fetchNext()">
</button>
</div>
You can try ngx-pagination for pagination in Angular 2+.

Categories

Resources