base_request.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2013 Strahinja Val Markovic <val@markovic.io>
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. import vim
  20. import json
  21. import requests
  22. from ycm import vimsupport
  23. HEADERS = {'content-type': 'application/json'}
  24. class ServerError( Exception ):
  25. def __init__( self, message ):
  26. super( ServerError, self ).__init__( message )
  27. class BaseRequest( object ):
  28. def __init__( self ):
  29. pass
  30. def Start( self ):
  31. pass
  32. def Done( self ):
  33. return True
  34. def Response( self ):
  35. return {}
  36. @staticmethod
  37. def PostDataToHandler( data, handler ):
  38. response = requests.post( _BuildUri( handler ),
  39. data = json.dumps( data ),
  40. headers = HEADERS )
  41. if response.status_code == requests.codes.server_error:
  42. raise ServerError( response.json()[ 'message' ] )
  43. # We let Requests handle the other status types, we only handle the 500
  44. # error code.
  45. response.raise_for_status()
  46. if response.text:
  47. return response.json()
  48. return None
  49. server_location = 'http://localhost:6666'
  50. def BuildRequestData( start_column = None, query = None ):
  51. line, column = vimsupport.CurrentLineAndColumn()
  52. request_data = {
  53. 'filetypes': vimsupport.CurrentFiletypes(),
  54. 'line_num': line,
  55. 'column_num': column,
  56. 'start_column': start_column,
  57. 'line_value': vim.current.line,
  58. 'filepath': vim.current.buffer.name,
  59. 'file_data': vimsupport.GetUnsavedAndCurrentBufferData()
  60. }
  61. if query:
  62. request_data[ 'query' ] = query
  63. return request_data
  64. def _BuildUri( handler ):
  65. return ''.join( [ BaseRequest.server_location, '/', handler ] )