Guest User

Untitled

a guest
Mar 23rd, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.64 KB | None | 0 0
  1. class API(SearchBaseHandler):
  2. def get_count(self, key):
  3. data = memcache.get(key)
  4. if data is not None:
  5. return data
  6. else:
  7. data = Ad.all().filter('published =',
  8. True).filter('modified >',
  9. datetime.datetime.now()
  10. - timedelta(days=90)).count(limit=10000)
  11. memcache.add(key, data, 36000)
  12. return data
  13.  
  14. def get_data(self, url, key, query, number=50):
  15. data = memcache.get(key)
  16. if data is not None and len(data.results) > 0:
  17. return data
  18. else:
  19. data = find_documents(url, query, number, search.Cursor())
  20. memcache.add(key, data, 36000)
  21. return data
  22.  
  23. def get_data_offset(self, url, key, query, page=1, results=20):
  24. data = memcache.get(key)
  25. if data is not None and len(data.results) > 0:
  26. return data
  27. else:
  28. data = find_documents_offset_api(query, results, (page-1) * results)
  29. memcache.add(key, data, 3600)
  30. return data
  31.  
  32. def get_data_companies(self, url, key, query):
  33. data = memcache.get(key)
  34. if data is not None and len(data.results) > 0:
  35. return data
  36. else:
  37. data = find_documents(url, query, 50, search.Cursor())
  38. memcache.add(key, data, 36000)
  39. return data
  40.  
  41.  
  42. def get_count(self, key):
  43. data = memcache.get(key)
  44. if data is not None:
  45. return data
  46. else:
  47. data = Ad.all().filter('published =',
  48. True).filter('modified >',
  49. datetime.now()
  50. - timedelta(days=90)).count(limit=10000)
  51. memcache.add(key, data, 36000)
  52. return data
  53.  
  54. def get(self):
  55. """Handles a get request with a query."""
  56. page = self.request.get('page')
  57. query = self.request.get('query')
  58. key = 'india-json-32_adlist-new' + self.request.host+page+query
  59. results = self.get_data_offset(self.request.host, key, query, page=int(page),results=20)
  60. dic = []
  61. import filters
  62. for scored_document in results:
  63. item = {}
  64. item["id"] = scored_document.fields[8].value
  65. item["title"] = scored_document.fields[0].value
  66. item["text"] = scored_document.fields[1].value
  67. item["img"] = filters.displayimg(scored_document.fields[8].value) #FIXME for item with no image
  68. dic.append(item)
  69. from webapp2_extras import json
  70. self.response.headers['Content-Type'] = 'application/json'
  71. self.response.write(json.encode({'results':dic}))
  72.  
  73. /api?page=1&query=java
  74.  
  75. def find_documents_offset_api(query_string, doc_limit, offsetn):
  76. try:
  77. date_desc = search.SortExpression(expression='date',
  78. direction=search.SortExpression.DESCENDING,
  79. default_value=datetime(1999, 01, 01))
  80.  
  81. hr_desc = search.SortExpression(expression='hour',
  82. direction=search.SortExpression.DESCENDING,
  83. default_value=1)
  84.  
  85. min_desc = search.SortExpression(expression='minute',
  86. direction=search.SortExpression.DESCENDING,
  87. default_value=1)
  88.  
  89. # Sort up to matching results by date in descending order
  90. sort = search.SortOptions(expressions=[date_desc, hr_desc,
  91. min_desc], limit=20)
  92.  
  93. # Set query options
  94. options = search.QueryOptions(limit=doc_limit, offset=offsetn,
  95. sort_options=sort,
  96. number_found_accuracy=20,
  97. # returned_fields=['title', 'city', 'region','category', 'adID', 'date','price', 'type', 'company_ad', 'adID', 'cityID','regionID', 'hour','minute'],
  98. #snippeted_fields=['text']
  99. )
  100. query = search.Query(query_string=query_string, options=options)
  101. index = search.Index(name=_INDEX_NAME)
  102. # Execute the query
  103. return index.search(query)
  104.  
  105. except search.PutError as e:
  106. logging.exception('caught PutError %s', e)
  107.  
  108. except search.InternalError as e:
  109. logging.exception('caught InternalError %s', e)
  110.  
  111. except search.DeleteError as e:
  112. logging.exception('caught DeleteError %s', e)
  113.  
  114. except search.TransientError as e:
  115. logging.exception('caught TransientError %s', e)
  116.  
  117. except search.InvalidRequest as e:
  118. logging.exception('caught InvalidError %s', e)
  119.  
  120. except search.Error as e:
  121. logging.exception('caught unknown error %s', e)
  122.  
  123. return None
  124.  
  125. import React, {Component} from 'react';
  126. import {
  127. ActivityIndicator,
  128. FlatList,
  129. StyleSheet,
  130. TouchableWithoutFeedback,
  131. View,
  132. Button, AsyncStorage, Alert
  133. } from 'react-native';
  134. import { List, ListItem } from "react-native-elements";
  135. import {Col, Row, Text, SearchBar } from 'react-native-elements';
  136.  
  137. class Trends extends Component {
  138.  
  139. constructor(props) {
  140. super(props);
  141.  
  142. this.state = {
  143. loading: false,
  144. data: [],
  145. page: 1,
  146. seed: 1,
  147. error: null,
  148. refreshing: false,
  149. text: '',
  150. };
  151. this.arrayholder = [] ;
  152. }
  153.  
  154. componentDidMount() {
  155. this.makeRemoteRequest();
  156. }
  157.  
  158. makeRemoteRequest = () => {
  159. const { page, seed, text } = this.state;
  160. const url = `https://www.koolbusiness.com/api?seed=${seed}&page=${page}&query=${text}&results=20`;
  161. this.setState({ loading: true });
  162.  
  163. fetch(url)
  164. .then(res => res.json())
  165. .then(res => {
  166.  
  167. this.setState({
  168. data: page === 1 ? res.results : [...this.state.data, ...res.results],
  169. error: res.error || null,
  170. loading: false,
  171.  
  172. refreshing: false
  173. }, function() {
  174.  
  175. });
  176. })
  177. .catch(error => {
  178. this.setState({ error, loading: false });
  179. });
  180. };
  181. handleRefresh = () => {
  182. this.setState(
  183. {
  184. page: 1,
  185. seed: this.state.seed + 1,
  186. refreshing: true
  187. },
  188. () => {
  189. this.makeRemoteRequest();
  190. }
  191. );
  192. };
  193.  
  194. handleLoadMore = () => {
  195. this.setState(
  196. {
  197. page: this.state.page + 1
  198. },
  199. () => {
  200. this.makeRemoteRequest();
  201. }
  202. );
  203. };
  204.  
  205. renderSeparator = () => {
  206. return (
  207. <View
  208. style={{
  209. height: 1,
  210. width: "86%",
  211. backgroundColor: "#CED0CE",
  212. marginLeft: "14%"
  213. }}
  214. />
  215. );
  216. };
  217. SearchFilterFunction(text){
  218. this.setState({
  219. data: [],
  220. text: text
  221. });
  222. this.handleRefresh();
  223. }
  224. renderHeader = () => {
  225. return <SearchBar onChangeText={(text) => this.SearchFilterFunction(text)}
  226. placeholder="Type Here..." lightTheme round />;
  227. };
  228. renderFooter = () => {
  229. if (!this.state.loading) return null;
  230. return (
  231. <View
  232. style={{
  233. paddingVertical: 20,
  234. borderTopWidth: 1,
  235. borderColor: "#CED0CE"
  236. }}
  237. >
  238. <ActivityIndicator animating size="large" />
  239. </View>
  240. );
  241. };
  242. render() {
  243. return (
  244. <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
  245. <FlatList
  246. data={this.state.data}
  247. renderItem={({ item }) => (
  248. <TouchableWithoutFeedback onPress={() => this.props.navigation.navigate('Details', { id: item.id })} >
  249.  
  250. <ListItem
  251. roundAvatar
  252. title={`${item.title}`}
  253. subtitle={item.text}
  254. avatar={{ uri: item.img }}
  255. containerStyle={{ borderBottomWidth: 0 }}
  256. />
  257. </TouchableWithoutFeedback>
  258. )}
  259. keyExtractor={item => item.id}
  260. ItemSeparatorComponent={this.renderSeparator}
  261. ListHeaderComponent={this.renderHeader}
  262. ListFooterComponent={this.renderFooter}
  263. onRefresh={this.handleRefresh}
  264. refreshing={this.state.refreshing}
  265. onEndReached={this.handleLoadMore}
  266. onEndReachedThreshold={50}
  267. />
  268. </List>
  269. );
  270. }
  271. }
  272.  
  273. const styles = StyleSheet.create({
  274. listHeader: {
  275. flex: 1,
  276. flexDirection: "row",
  277. marginLeft: 10,
  278. marginTop: 5,
  279. },
  280. container: {
  281. flex: 1,
  282. },
  283. headerContainer: {
  284. justifyContent: 'center',
  285. alignItems: 'center',
  286. padding: 40,
  287. backgroundColor: '#FD6B78'
  288. },
  289. heading: {
  290. color: 'white',
  291. marginTop: 10,
  292. fontSize: 22,
  293. },
  294. text: {
  295. marginLeft: 20,
  296. flex: 1
  297. },
  298. image: {
  299. marginRight: 20,
  300. width: 30,
  301. height: 30,
  302. flex: 3,
  303. }
  304. });
  305.  
  306. export default Trends;
Add Comment
Please, Sign In to add comment