Я создаю приложение, используя бэкэнд Django / Python и интерфейс React / JavaScript. Приложение использует Axios для импорта данных из другого приложения с помощью API. Я развернул приложение в Heroku, и 4 из 5 импортов успешно работают, но один из них не работает в Heroku (но работает локально). Импорт содержит разумное количество данных и занимает самый длинный из 5 операций импорта. Может кто-нибудь помочь мне определить проблему?
Это ошибка:
createError.js:16 Uncaught (in promise) Error: Request failed with status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.f.onreadystatechange (xhr.js:59)
Это компонент React:
import React, { Component } from 'react'
import axios from 'axios'
import { formatTimeDate } from '../../lib/helpers'
class CrewLoader extends Component {
constructor() {
super()
this.state = {
loading: false,
crewDataUpdated: ''
}
this.getData = this.getData.bind(this)
}
async getData() {
this.cancelTokenSource = axios.CancelToken.source()
this.setState({ loading: true })
try {
const crews = await axios.get('/api/crew-data-import', {
cancelToken: this.cancelTokenSource.token
})
console.log(crews.data)
this.setState({ crewDataUpdated: Date.now(), loading: false })
} catch (err) {
if (axios.isCancel(err)) {
// ignore
} else {
// propegate
throw err
}
} finally {
this.cancelTokenSource = null
}
}
componentWillUnmount() {
this.cancelTokenSource && this.cancelTokenSource.cancel()
}
render() {
const { loading } = this.state
return (
<div>
<button className="button is-primary" onClick={this.getData} disabled={loading}>
{loading && <span className="spinner"><i
className="fas fa-spinner fa-spin"
/> Loading ...</span>}
{!loading && <span>Get Crew data</span>}
</button>
<p><small>{!this.state.crewDataUpdated ? '' : `Updated: ${formatTimeDate(this.state.crewDataUpdated)}`}</small></p>
</div>
)
}
}
export default CrewLoader
Это view.py:
class CrewDataImport(APIView):
def get(self, _request):
# Start by deleting all existing crews and times
Crew.objects.all().delete()
RaceTime.objects.all().delete()
Meeting = os.getenv("MEETING2019") # Competition Meeting API from the Information --> API Key menu
UserAPI = os.getenv("USERAPI") # As supplied in email
UserAuth = os.getenv("USERAUTH") # As supplied in email
header = {'Authorization':UserAuth}
request = {'api_key':UserAPI, 'meetingIdentifier':Meeting}
url = 'https://webapi.britishrowing.org/api/OE2CrewInformation' # change ENDPOINTNAME for the needed endpoint eg OE2MeetingSetup
r = requests.post(url, json=request, headers=header)
if r.status_code == 200:
# pprint(r.json())
for crew in r.json()['crews']:
data = {
'name': crew['name'],
'id': crew['id'],
'composite_code': crew['compositeCode'],
'club': crew['clubId'],
'rowing_CRI': crew['rowingCRI'],
'rowing_CRI_max': crew['rowingCRIMax'],
'sculling_CRI': crew['scullingCRI'],
'sculling_CRI_max': crew['scullingCRIMax'],
'event': crew['eventId'],
'status': crew['status'],
'bib_number': crew['customCrewNumber'],
'band': crew['bandId'],
}
serializer = WriteCrewSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
crews = Crew.objects.all()
serializer = WriteCrewSerializer(crews, many=True)
return Response(serializer.data)
return Response(status=400)
URL проекта:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('django-admin/', admin.site.urls),
path('auth/', include('rest_framework.urls')),
path('api/', include('results.urls')),
path('api/', include('jwt_auth.urls')),
path('', include('frontend.urls')),
]