如何解决状态创建请求后,Flask 不发送响应数据以响应本机
我正在做一个 React-Native 应用项目;为此,我正在使用 @flask_classful 在 Python Flask 中开发 API。该应用程序具有创建状态/发布功能和 python Flask 中的路由;并使用 Flask API 取回所有状态。当我启动 Python Flask 服务器和应用程序时,一切正常。
但我在以下场景中遇到了问题
-
当我创建新状态时
-
在初始请求时,同一路由发送用户发布的所有状态,
-
但在发布/创建新状态后,路由发送空响应。
当我退出 python Flask 服务器并重新启动它时,一切又正常了。
这是我的代码
class Statuses(FlaskView):
response = dict({"isLoggedIn": True})
bl = StatusesBL()
ubl = UsersBL()
cbl = CommentBL()
#route for fetching satuses
def index(self):
offset = 0
response = dict({"isLoggedIn": True})
user = AuthorizeRequest(request.headers)
if not user:
return jsonify(notLoggedIn)
if "offset" in request.args:
offset = int(request.args.get("offset")) * 10
statuses = BL.getBL("status").getStatusesForFeed(user,offset)
response.update({"statuses": statuses})
return jsonify(response)
@route("/upload",methods=["GET","POST"])
def upload_media(self):
response = dict({"isLoggedIn": True})
user = AuthorizeRequest(request.headers)
if not user:
return jsonify(notLoggedIn)
if request.method == "GET":
pass
elif request.method == "POST":
if request.form["status"] == "" and not request.files:
response.update(
{"isstatusPosted": False,"status": "Enter text or upload images."}
)
return jsonify(response)
data = {
"status": None,"media": {"images": [],"video": []},}
media = list()
status_text = request.form["status"]
data["status"] = status_text
if request.files:
files = request.files
images = files.getlist("images[]")
for image in images:
dt_obj = datetime.strptime(
str(datetime.Now()),"%Y-%m-%d %H:%M:%s.%f"
)
millisec = str(dt_obj.timestamp() * 1000)
time = millisec.replace(".","")
image_name = user.first_name + str(user.user_id) + time + ".jpg"
media.append(image_name)
folder = os.path.join(app.root_path,'static/user/status')
file_path = os.path.join(folder,image_name)
image.save(file_path)
data["media"] = {"images": media,"video": []}
isstatusPosted,status = BL.getBL("status").addUserStatus(user,data)
response.update({"isstatusPosted": isstatusPosted,"status": status})
print(response)
return jsonify(response)
else:
return "invalid request"
以下是反应原生屏幕:
import * as React from 'react';
import { StyleSheet,FlatList,TouchableOpacity,Image,Text,View,ActivityIndicator } from 'react-native';
import { get } from '../apis/';
import LikeComponent from './Feed/LikeComponent';
import CommentComponent from './Feed/CommentComponent';
import ShareComponent from './Feed/ShareComponent';
import ratingStarsComponent from './Feed/ratingStarsComponent';
import SwapBtnComponent from './Feed/SwapBtnComponent';
import CarouselComponent from './Feed/CarouselComponent.js';
import DropdownAlert from 'react-native-dropdownalert';
import { getProfileImage } from './shared/utils.js'
import axios from 'react-native-axios'
export default class Feed extends React.Component {
state = {
dialogVisibility: false,isLoggedIn: false,user: [],statuses: [],isRefreshing: true,isLoading: true,offset: 0,token: null,exTradata: true,};
async fetchStatuses() {
const ms = Date.Now();
console.log("before: " + this.state.statuses.length)
const statuses = await get(this,'statuses/?offset=0&ms=' + ms);
if (statuses.status) {
const res = statuses.response
console.log(res);
this.setState({ statuses: res.statuses,isRefreshing: false,isLoading: false,exTradata: !this.state.exTradata },() => {
console.log(this.state.statuses)
console.log("after: " + this.state.statuses.length)
});
} else {
this.setState({ isRefreshing: false,isLoading: false })
}
}
async componentDidMount() {
// this.props.navigation.addListener('focus',async () => {
// this.setState({ isRefreshing: true },() => this.fetchStatuses())
// })
this.fetchStatuses()
}
actionCallBack = (action,msg) => {
this.dropDownAlertRef.alertWithType(action,msg);
}
onRefresh = async () => {
this.setState({ isRefreshing: true },() => this.fetchStatuses());
// const ms = Date.Now();
// const statuses = await get(this,'statuses/?offest=0&ms=' + ms);
// if (statuses.status) {
// const res = statuses.response
// // this.setState({ statuses: null });
// this.setState({ statuses: res.statuses,isLoading: false });
// } else {
// this.setState({ isRefreshing: false,isLoading: false })
// }
}
getMoreTen = async () => {
await this.setState({ offset: this.state.offset += 1 })
const statuses = await get(this,'statuses/?offset=' + this.state.offset);
if (statuses.status) {
const res = statuses.response
this.setState({ statuses: this.state.statuses.concat(res.statuses),exTradata: !this.state.exTradata });
} else {
this.setState({ isRefreshing: false,isLoading: false })
}
}
getProfilePic = (status) => {
if (status.is_club_status) {
return status.club_profile_pic
} else if (status.is_app_status) {
// return getEndPointUrl()+'/static/'
return ''
}
}
goToProfile = (status) => {
if (status.is_club_status == 1) {
this.props.navigation.navigate('CountryClubs',{ screen: 'SingleClub',params: { club_id: status.club_id } });
} else if (status.is_app_status == 1) {
// return getEndPointUrl()+'/static/'
return ''
} else if (status.is_player_status == 1) {
this.props.navigation.navigate('PlayerProfile',{ player_id: status.player_id })
}
}
getProfileImage = (status) => {
if (status.is_club_status == 1) {
return getProfileImage('clubs',status.club_profile_pic)
} else if (status.is_app_status == 1) {
console.log(status)
return getProfileImage('user',status.club_profile_pic)
} else if (status.is_player_status == 1) {
return getProfileImage('player',status.player_profile_pic)
}
}
componentwillUnmount() {
// this.props.navigation.removeEventListener('focus')
}
render() {
if (this.state.isLoading) {
return (
<View style={{ justifyContent: 'center',flexDirection: 'column',flex: 1,alignContent: 'center' }}>
<ActivityIndicator size="large" color="green" style={{ alignSelf: 'center' }} />
</View>
)
}
return (
<View style={{ height: '100%' }}>
<FlatList style={styles.list}
data={this.state.statuses}
exTradata={this.state.exTradata}
keyExtractor={(item) => {
// console.log(item)
return item.status_id != null ? item.status_id : "0";
}}
refreshing={this.state.isRefreshing}
onRefresh={() => this.onRefresh()}
ItemSeparatorComponent={() => {
return (
<View style={styles.separator} />
)
}}
onEndReachedThreshold={0}
onEndReached={this.getMoreTen}
renderItem={(item) => {
const status = item.item;
return (
<View style={styles.card} >
<View style={styles.cardHeader}>
<View>
<View style={{ flexDirection: 'row',alignItems: 'center' }}>
<TouchableOpacity onPress={() => this.goToProfile(status)}>
<Image style={{ width: 60,height: 60,borderRadius: 30 }}
source={{ uri: this.getProfileImage(status) }} />
</TouchableOpacity>
<TouchableOpacity onPress={() => this.goToProfile(status)}>
<Text style={{ fontSize: 16,fontWeight: 'bold',marginLeft: 12 }}>{status.club_name}</Text>
</TouchableOpacity>
</View>
<Text onPress={() => this.props.navigation.navigate('SingleFeed',{ status_id: status.status_id })} style={styles.description}>{status.status_description}</Text>
<CarouselComponent media={status.status_media} />
<ratingStarsComponent status={status} />
<View style={styles.timeContainer}>
<Image style={styles.iconData} source={{ uri: 'https://img.icons8.com/color/96/3498db/calendar.png' }} />
<Text style={styles.time}>{status.created_at}</Text>
</View>
</View>
</View>
<View style={styles.cardFooter}>
<View style={styles.socialBarContainer}>
<LikeComponent showAlert={this.actionCallBack} token={this.state.token} status={status} />
<CommentComponent showAlert={this.actionCallBack} token={this.state.token} status={status} />
<ShareComponent status={status} />
<SwapBtnComponent
navigation={this.props.navigation}
status={status}
is_club={status.is_club_status == 1 ? true : false}
showAlert={this.actionCallBack}
/>
</View>
</View>
</View>
)
}} />
<DropdownAlert ref={ref => this.dropDownAlertRef = ref} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,marginTop: 20,},list: {
paddingHorizontal: 17,backgroundColor: "#E6E6E6",separator: {
marginTop: 10,/******** card **************/
card: {
shadowColor: '#00000021',shadowOffset: {
width: 2
},shadowOpacity: 0.5,shadowRadius: 4,marginVertical: 8,backgroundColor: "white",width: '100%'
},cardHeader: {
paddingVertical: 17,paddingHorizontal: 16,borderTopLefTradius: 1,borderTopRighTradius: 1,flexDirection: 'row',justifyContent: 'space-between',cardContent: {
paddingVertical: 12.5,width: '100%',cardFooter: {
flexDirection: 'row',paddingTop: 10,paddingBottom: 2,paddingHorizontal: 2,borderBottomLefTradius: 1,borderBottomrighTradius: 1,backgroundColor: "#EEEEEE",cardImage: {
flex: 1,height: 150,/******** card components **************/
title: {
fontSize: 18,description: {
fontSize: 15,color: "#888",marginTop: 15,marginBottom: 8,time: {
fontSize: 13,color: "#808080",marginTop: 5,icon: {
width: 25,height: 25,iconData: {
width: 15,height: 15,marginRight: 5
},timeContainer: {
flexDirection: 'row',/******** social bar ******************/
socialBarContainer: {
justifyContent: 'center',alignItems: 'center',padding: 8
},socialBarSection: {
justifyContent: 'center',socialBarlabel: {
marginLeft: 8,alignSelf: 'flex-end',justifyContent: 'center',socialBarButton: {
flexDirection: 'row',}
});
请检查,并帮助我摆脱这种有问题的情况。过去 10 天我都被困在其中。
谢谢。
解决方法
问题已解决。我正在使用工厂模式,这是由于这个原因。我已经更正了工厂电话。现在运行正常
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。